JQuery: Change value of hidden input field

2019-03-22 15:24发布

I'm having a hella time setting the value of a hidden input.

I want to pass the HTML from between the option tags to the hidden field- end run it will the page title from wordpress' wp_list_dropdowns(). I've got it returning the text just fine, and on my change event it correctly adds some css (obviously unneeded on a hidden field, but I was trying to determine where things are breaking down). Works if I change the hidden input to a text input. I've seen in several places on SO that this is possible, (changing the value of a hidden input that is), but something is holding me up now and I can't see the answer.

Here's the JSFiddle:

JavaScript:

$(".selector").change(function() {
    var $value = $(this).val();
    var $title = $(this).children('option[value='+$value+']').html();
    alert($title); 
    $('input#bacon').val($title).css('border','3px solid blue');
});

HTML:

<select class="selector" name="testselect">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>
</h3>

<input id="bacon" type="hidden" class="bacon" value="" name="testinput">

4条回答
一夜七次
2楼-- · 2019-03-22 15:25

Seems to work

$(".selector").change(function() {

    var $value = $(this).val();

    var $title = $(this).children('option[value='+$value+']').html();

    $('#bacon').val($title);

});

Just check with your firebug. And don't put css on hidden input.

查看更多
成全新的幸福
3楼-- · 2019-03-22 15:31

If you're doing this in Drupal and use the Form API to change the #type from text to 'hidden' in hook_form_alter (for example), be advised that the output HTML will have different (or omitted) DIV wrappers, IDs and class names.

查看更多
萌系小妹纸
4楼-- · 2019-03-22 15:37

Your jQuery code works perfectly. The hidden field is being updated.

查看更多
Rolldiameter
5楼-- · 2019-03-22 15:46

It's simple as:

$('#action').val("1");

#action is hidden input field id.

查看更多
登录 后发表回答