javascript - How to assign a var value to jQuery .val() - Stack Overflow

admin2025-04-26  6

I get value from checkFields method and then I assign it to hidden variable searchValidate. The value of atleastOneFilled will be true or false .Below is the code

var atleastOneFilled = checkFields($("#searchForm"));
alert('atleastOneFilled' + atleastOneFilled );
$('#searchValidate').val(atleastOneFilled);  

But the value is not getting set to searchValidate. The alert displays the correct value but still not assigned to searchValidate. Is it something a wrong way of assigning to .val()

HTML:

<input type="hidden" value="" th:name="searchValidate"/>

I get value from checkFields method and then I assign it to hidden variable searchValidate. The value of atleastOneFilled will be true or false .Below is the code

var atleastOneFilled = checkFields($("#searchForm"));
alert('atleastOneFilled' + atleastOneFilled );
$('#searchValidate').val(atleastOneFilled);  

But the value is not getting set to searchValidate. The alert displays the correct value but still not assigned to searchValidate. Is it something a wrong way of assigning to .val()

HTML:

<input type="hidden" value="" th:name="searchValidate"/>
Share Improve this question edited Jun 9, 2015 at 3:43 Java_User asked Jun 9, 2015 at 3:38 Java_UserJava_User 4753 gold badges12 silver badges30 bronze badges 5
  • What does your html look like? – Jesse Kernaghan Commented Jun 9, 2015 at 3:39
  • What type of field is #searchValidate? – Alex McMillan Commented Jun 9, 2015 at 3:40
  • What kind of element is #searchValidate? – Felix Kling Commented Jun 9, 2015 at 3:41
  • How do you check that it is not assigned? – Kirill Slatin Commented Jun 9, 2015 at 3:42
  • I have edited the question with HTML – Java_User Commented Jun 9, 2015 at 3:44
Add a ment  | 

4 Answers 4

Reset to default 2

you need to use a different jquery selector:

$('input[name="searchValidate"]').val(atLeastOneField);

the # signifies the id property of an element

The issue is happening because you are using id selector in jQuery to set the value and the input element is missing the id attribute. So please change the html as shown below and it will work

<input type="hidden" value="" id="searchValidate" th:name="searchValidate"/>

I think you can't select when attributes contain ":" you need to use foreach loop and match attributes .

 var atleastOneFilled = checkFields($("#searchForm"));
    alert('atleastOneFilled' + atleastOneFilled );

$( "input[type='hidden']" ).each(function(){

if($( "input" ).attr("th:name")="searchValidate")
{
    $('#searchValidate').val(atleastOneFilled);  

}

});

maybe try

$('#searchValidate').text(atleastOneFilled); 

instead of

$('#searchValidate').val(atleastOneFilled); 
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745662303a312817.html

最新回复(0)