admin管理员组文章数量:1410697
I have this code which works fine!:
<script>
function get(userfirstname, userlastname){
alert(userfirstname);
return false;
}
</script>
<form action="" method="POST">
<input type="text" name="userfirstname">
<input type="text" name="userlastname">
<input type="submit" onclick="return get(userfirstname.value, userlastname.value);">
</form>
I have this code which works fine!:
<script>
function get(userfirstname, userlastname){
alert(userfirstname);
return false;
}
</script>
<form action="" method="POST">
<input type="text" name="userfirstname">
<input type="text" name="userlastname">
<input type="submit" onclick="return get(userfirstname.value, userlastname.value);">
</form>
i am trying to catch the input values with an array like this:
<script>
function get(user){
alert(user["firstname"].value);
return false;
}
</script>
<form action="" method="POST">
<input type="text" name="user[firstname]">
<input type="text" name="user[lastname]">
<input type="submit" onclick="return get(user);">
</form>
i tried so many different scenarios, no point :(
Any hint would be appreciated.
Share Improve this question edited Aug 14, 2016 at 17:05 Tarık Seyceri asked Aug 14, 2016 at 16:51 Tarık SeyceriTarık Seyceri 4632 gold badges9 silver badges16 bronze badges 2- 1 you can't.. in js you have to get them in objects to do this – Akshay Khandelwal Commented Aug 14, 2016 at 16:53
- hello!, thank you for your ment, how can i get them in object? – Tarık Seyceri Commented Aug 14, 2016 at 16:57
2 Answers
Reset to default 2You could simply target the form
element inside your onclick
handler, query all input
elements to iterate over them and build the array
you are looking for.
Here is an example of what you could do to build an array of objects holding each input elements name and value, excluding disabled once and the submit element.
function get(evt){
var fields = [];
event.target.parentElement
.querySelectorAll('input:not([disabled]):not([type="submit"])').forEach(function(e) {
fields.push({name: e.name, value: e.value});
})
console.log(fields);
return false;
}
<form>
<input type="text" name="firstname" placeholder="Name"><br>
<input type="text" name="lastname" placeholder="Surename"><br>
<input type="text" name="foo" value="foo will be excluded" disabled><br>
<input type="submit" onclick="return get();">
</form>
A jQuery Approach to get this
function get(){
var fields = [];
var arr = $('form').not('input[type="submit"]').find('input[type="text"]')
$(arr).each(function(i,val){
fields.push({name:$(val).attr('name'),value:$(val).val()})
})
}
本文标签: HTML Input Array How to get html input array values with javascriptStack Overflow
版权声明:本文标题:HTML Input Array: How to get html input array values with javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744278591a2598538.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论