开发者

jQuery checked attribute

I'm completely stumped. I have no clue why this isn't working and it seems so simple to me. It's simply supposed to check whether the checkbox is checked and transfer the value of the textbox. Instead this just pops up an alert at page load and then nothing after that.

$(function(){开发者_StackOverflow中文版
if($("#same").is(":checked"))
{
    alert("checked");
    $("#name2").val($("#name1").val());
}
else
{
    alert("unchecked");
    $("#name2").val("");
}
});

Things I've tried:

if($("#same").attr("checked"))
adding == true on the end
$("#same").click($(this.toggle(...))) // this semi worked but toggled on and off improperly

The checkbox does have an id of "same" before it is asked.

What is wrong with this code? Like I said I'm stumped! Thanks :)

Edit 1: As requested here is an html snippet.

<div class="tkfmheader">Info 2 <span class="tkshcbx">Same as 1 <input type="checkbox" name="same" id="same" /></span></div>


A function like this is only handled once, on pageload.

If you want this alert to do something every time you click, you will need to set the function to an event: like the click() event, or the change() event.

You could try something like:

// just a default way to assign functions in the ready event:
$(document).ready(function()
{
    // add an event to some element
    // the change event will work too (see link, it says about checkboxes)
    // you can also add an event to every checkbox instead of just #same
    $('#same').click(function()
    {
        // your alert function here
        // you can ask things to #same by using $(this)
    });
});


try:

if($("#same:checked").length > 0)

if it's greater than 0, it's checked


Is this what you are looking for

$(':checkbox').click(function() {
    $(this).is(":checked") ? $("#name2").val($("#name1").val()) : $("#name2").val("");   
});

Check working example at http://jsfiddle.net/XbCAL/1/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜