Setting the value of a hidden input

六月ゝ 毕业季﹏ 提交于 2019-12-11 12:52:59

问题


The idea: I'm setting the value of an input with type="hidden" via regular Javascript or jQuery.

The issue: neither jQuery nor document.getElementById will find the hidden input, even though I'm absolutely sure the selector is correct and there are no conflicting elements.

The code: I can't really post much of it, because it's full of rather complicated PHP that confuses me when I just look at it.

Here's the javascript:

$("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total);

Note: there's nothing wrong with the selector, and the "input" is a different element that I'm using to reference the hidden.

Here's the HTML:

<input type="hidden" name="s<?=$step_counter?>_budget_hidden" 
       id="s<?=$step_counter?>_budget_hidden" value="0" />

The code is kind of out of context, but it's more of a general problem with Javascript than a syntactical error. Thoughts?


回答1:


In $("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total); you take two chars before the first underscore in your hidden id. However your hidden id have only one char 's'

EDIT

Ok the <?= ?> was hidden before the question edit.

Do you call your script after the body onload event? EX:

$(document).ready(function(){
    $("#" + input.id.substr(0,2) + "_budget_hidden").bind("keyPressed",function(){
        $("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total);
     }
});



回答2:


FYI: We can get the hidden input value using jQuery, even we can also edit any hidden input value using jQuery.

I think your way of getting the hidden value using 'substr' method is causing some problem. You are using like substr(0, 2) so are sure that the variable $step_variable is a single digit number, otherwise your code will not return correct result.

I am giving some sample code below, check it once.

Here's the javascript:

    var input_id = $("hidden_val").attr("id").substr(1);
    $("#" + input_id + "_budget_hidden").val(budg_total);

Here's the HTML:

    input type="hidden" class="hidden_val" name="s_budget_hidden" id="s" value="0" 

I think this will help you. Let me know if you are not following this flow to solve your issue.




回答3:


I think that input.id.substr(0,2) says to start at the start of the string, take 2 characters and use that.

http://www.w3schools.com/jsref/jsref_substr.asp

Try using Firebug to see what the result of that method call is.



来源:https://stackoverflow.com/questions/3197346/setting-the-value-of-a-hidden-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!