开发者

Locating Hidden Field Using JQuery

开发者 https://www.devze.com 2023-02-24 06:40 出处:网络
Boiled down to the barest element, I just want to set a hidden field\'s value when I click an element on the page.

Boiled down to the barest element, I just want to set a hidden field's value when I click an element on the page.

HTML:

<div id="toggleParent">
  <input type="hidden" name="to开发者_高级运维ggleValue" id="toggleValue" value="closed" />
  <h2>Click Me</h2>
</div>

jQuery:

jQuery(document).ready(function() {
  var toggle;
  jQuery('div#toggleParent h2').click(function () {
    if (toggle == '' || toggle == 'open') {
      toggle = 'closed';
    } else {
      toggle = 'open';
    }
    jQuery('div#toggleParent input#toggleValue').val(toggle);
  });
});

Obviously, it's not working. (Why would I be here otherwise?) The click event is working fine, as I can step through it in Firebug. But when it gets to setting the value, the code fails. What's more, trying alert(jQuery('div#toggleParent input#toggleValue').length) returns 0. In fact, alert(jQuery('div#toggleParent h2').length) returns 0 even though the click event on that exact element just fired!

What am I missing?


This:

document.ready(function () {...});

Should be:

jQuery(document).ready(function () {...});

Or even:

jQuery(function () {...});

Or...

jQuery(function ($) { /* Use $ in here instead of jQuery */ });

Keep in mind that when using IDs, any other selector is unnecessary since IDs are unique. This is sufficient:

jQuery('#toggleValue').val(toggle);


Your 'toggle' value is undefined, you only define it in document.ready, but do not assign any value to it. To assign, use

var toggle = jQuery('div#toggleParent input#toggleValue').val();


I propose this code:

jQuery(function($) {

    var toggleParent = $('#toggleParent')[0],
        toggleValue = $('#toggleValue')[0];

    $(toggleParent).find('h2').click(function() {
        toggleValue.value = toggleValue.value === 'closed' ? 'open' : 'closed';
    });

});


Try this code:

$(document).ready(function() {
            var toggle;
            $('div#toggleParent h2').click(function() {
                if (toggle == '' || toggle == 'open') {
                    toggle = 'closed';
                } else {
                    toggle = 'open';
                }
                $('div#toggleParent input#toggleValue').val(toggle);
                alert($("input#toggleValue").val()); // check what the new value is
            });
        });
0

精彩评论

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