Can someone please let me know how to get values from several input fields?
I have a list with several inputs like this:
<li>
<label>Additional Title: </label><input type='text' name='additionaltitlename' ... />
</li>
<li>
<label>Additional Title: </label><input type='text' name='additionaltitlename' ... />
</li>
I have a solution in Javascript (on form submit):
...
var extratitles = document.getElementsByName('additionaltitlename');
var str = '';
for (var i = 0; i < extratitles.length; i++) {
str = str + '|' + extratitles.item(i).value;
}
}
How do I do the same thing in JQuery?
It's not valid to have two inputs of the same name. If you want to do this, you can use <input name="titles[]">
You can try this:
<input name="titles[]">
<input name="titles[]">
<button>submit</button>
With this jQuery
// click handler
function onClick(event) {
var titles = $('input[name^=titles]').map(function(idx, elem) {
return $(elem).val();
}).get();
console.log(titles);
event.preventDefault();
}
// attach button click listener on dom ready
$(function() {
$('button').click(onClick);
});
See it working here on jsFiddle
EDIT
This answer gives you the titles in an array instead of a string using a | separator. Personally, I think this is a lot more usable.
If you're just submitting the form and you want to support multiple values, use the .serialize method as described in the other answer
Use jQuery's native serialize function:
var data = $('input[name="additionaltitlename"]').serialize();
docs
The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements.
It is very easy in jquery. you can do this as:
types = [];
$("input[name='additionaltitlename']").each(function() {
types.push($(this).val());
});
console.log(types);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="additionaltitlename1" name="additionaltitlename" class="form-control" value="abc">
<input type="text" id="additionaltitlename2" name="additionaltitlename" class="form-control" value="xyz">
In addition to #gdoron's or #macek's answer which are probably the way to go, I'd like to add that all that is wrong with the code you have posted is that you have one } too much. This works (although it still has room for improvement):
$('#getpreviewbutton').click(function(){
var extratitles = document.getElementsByName('additionaltitlename');
var str = '';
for (var i = 0; i < extratitles.length; i++) {
str = str + '|' + extratitles.item(i).value;
}
});
See: http://jsfiddle.net/8XJcc/
I don't know which browser you are using but using sth like Firebug or the Chrome Dev Tools can be pretty handy to spot simple mistakes like this. See this reference for Chrome or this one for Firefox. Even IE has one - just press F12.
Means:
str = '';
$("input[type='text']").each(function() {
str = str + '|' + $(this).val();
});
or
str = '';
$("input[name='additionaltitlename']").each(function() {
str = str + '|' + $(this).val();
});
?
Related
I have a div in which I render through javascript inputs and text dynamically. I am trying to capture the text of this div (both input values and text).
My first step if to capture the parent div:
let answerWrapper = document.getElementById("typing-answer-wrapper");
The issue now is that using the innerHTML will give me the whole html string with the given tags and using the inerText will give me the text, excluding the tags.
In the following case scenario:
the console inspect is:
What is the way to capture: $2.4 if the inputs have 2 and 4
and $null.null if the inputs are blank.
Any help is welcome
You could iterate over all of the element's child nodes and concatenate their wholeText or value else 'null'. For inputs the wholeText will be undefined. If they have no value we'll return 'null'. Be aware that spaces and line-breaks will also be included so you may want to strip these later (or skip them in the loop) but as a proof of concept see the following example:
var typingAnswerWrapper = document.getElementById("typing-answer-wrapper");
function getVal(){
var nodeList = typingAnswerWrapper.childNodes;
var str = "";
for (var i = 0; i < nodeList.length; i++) {
var item = nodeList[i];
str+=(item.wholeText || item.value || "null");
}
console.log(str);
}
getVal();
//added a delegated change event for demo purposes:
typingAnswerWrapper.addEventListener('change', function(e){
if(e.target.matches("input")){
getVal();
}
});
<div id="typing-answer-wrapper">$<input type="number" value=""/>.<input type="number" value="" />
</div>
Here's how you could do it :
function getValue() {
var parent = document.getElementsByClassName('typing-answer-wrapper')[0],
text = [];
const children = [...parent.getElementsByTagName('input')];
children.forEach((child) => {
if (child.value == '')
text.push("null")
else
text.push(child.value)
});
if (text[0] != "null" && text[1] == "null") text[1] = "00";
document.getElementById('value').innerHTML = "$" + text[0] + "." + text[1]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div class="typing-answer-wrapper">
$
<input type="number"> .
<input type="number">
</div>
<button onclick="getValue()">get value</button>
<div id="value"></div>
You can fetch input feild values by their respective ids $('#input_feild_1').val() will give the first feild value and similarly $('#input_feild_2').val() for second feild and contruct use them to construct whatever as u wish. As in your case this should work
value_1 = $('#input_feild_1_id').val()
value_2 = $('#input_feild_2_id').val()
you need something like "$ + value_1 + . + value_2"
Below is simple HTML:
<input type="text" class="form-control" id="user[0].first_name" name="user[0].first_name" placeholder="First Name">
And here's the JS:
emailIndex = 0;
for (var i = 0; i <= emailIndex; i++) {
data["user[" + i + "].first_name"] = $("#user[" + i + "].first_name").val();
}
If I try to print the ID user[0].first_name returns: undefined
What's wrong there?
Thanks!
in above code, #user[" + i + "].first_name after execute it will be #user[0].first_name
here, the jquery wont check like where id = user[0].first_name
but it will consider it as a id = user[0] and class = first_name
so, you wont get correct results in jquery but you can do it with javascript
DEMO
This works !
for (var i = 0; i <= emailIndex; i++) {
alert($('#user_'+i.toString()+'_first_name').val());
}
We need to change integer to string first.
Also dont forgot to take out dot operator from the id (see Nagesh's answer)
Happy coding.
In Javascript, You can't give id="user[0].first_name".
Instead, try to create 'input' elements using jQuery based on number of users like
$.each(users, function(index, user){
$(body).append('<input id="'+user.first_name+'"></input>');
});
OR
$(body).append('<input id="'+user[0].first_name+'"></input>');
Now
You can get val() of it by JS code You wrote
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am using a HTML page where I have multiple textbox inputs, lets say five for example. I have a submit button. Once I enter all values in the text boxes and hit submit, i want all the values to be displayed in the area below submit button on the document in an ascending order. I want to sort all the values to display as result. I just used an array to test if my concept is right, but no luck. Anyone could help is highly appreciated.
This is the code:
function myFunction() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
}
The .text-1, .text-2, etc are the classes of your input fields. The .val() will get the user input of those once they click on your submit button. The last line creates a new div and appends the user input to the results div.
$('.submit-button').on('click', function() {
aaa = $('.text-1').val();
bbb = $('.text-2').val();
ccc = $('.text-3').val();
ddd = $('.text-4').val();
eee = $('.text-5').val();
$('<div>' + aaa + '<br />' + bbb + '<br />' + ccc + '<br />' + ccc + '<br />' + ddd + '<br />' + eee + '</div>').appendTo('.results-div');
});
Here is a fiddle that does what I think you want done:
http://jsfiddle.net/KjHB3/3/
Here is the HTML code:
<input type="text" name="text1" id="text1" /><br/>
<input type="text" name="text2" id="text2" /><br/>
<input type="text" name="text3" id="text3" /><br/>
<input type="text" name="text4" id="text4" /><br/>
<input type="text" name="text5" id="text5" /><br/>
<input type="button" value="submit" id="submit" />
<div id="result">replace</div>
Here is the javascript code:
$("#submit").click(function() {
// Extract all the values into an array
var valArray = [];
$("input[type=text]").each(function(index, el) {
valArray[index] = jQuery(el).val();
});
// Output list of values (in order they appear in form)
$("#result").html("In order of text box: <ol id='list1'></ol>");
$.each(valArray, function(index, value) {
$("#list1").append("<li>" + value + "</li>");
});
// Output list of values (in sorted order)
$("#result").append("In sorted order: <ol id='list2'></ol>");
valArray = valArray.sort();
$.each(valArray, function(index, value) {
if (value != null && value != "") {
$("#list2").append("<li>" + value + "</li>");
}
});
});
Your code appears to be correct, except for the line document.getElementById('txt[i]').value + ' ';. There's nothing writing the values back to the document.
First, starting with the selector, you need to change 'txt[i]' to 'text'+i, because the browser is looking for an element with id txt[i] and finding nothing, thus doing nothing. Also, you should use jQuery, since it makes everything more concise.
Then, to write back to the document, you need to set the value. What your current code (.value + ' ';) does is it gets a value, then adds it to the string ' ', then the statement ends. What you need to do is to set the value of the string, with jQuery (.val(txt[i]);) or stock Javascript (.value = txt[i];).
So, to conclude, just swap the code inside the for loop in your code with this line:
$("input:text[name=text"+i+"]").val(txt[i]);
Let me break down your code in two part to show why it is not working yet.
function GetInputValues() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
return txt; // added by me to encapsulate getting the values
}
The first part of your function myFunction() is correct. You are using jQuery to get the values of the input boxes and writing the values into an array.
The second part has some mistakes:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
The function document.getElementById("lastname") returns the html-element whose id is lastname. So in your for-loop you are trying to get the value but you already have the values in your array txt. On top this 'txt[i]' is only a string. So javascript tries to find an element that matches <... id="txt[i]" ...>. But you do not want to get the values you want to write the values back into the document. Assuming you have a div like this <div id='txt[i]'> ...</div> you could wrhite your code like this:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').innerHTML += txt[i];
}
Another way would be to join the array:
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
This assumes that you have a element with id=myResult for example <div id='myResult'>..</div>
Update to adress issues in your code
Your fiddle has this part:
myFunction(txt) { // <-- function declaration: there is something missing here
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
} //<--- this is the end of myfunction
}); // <-- these do not belong here
// you never execute myFunction
You have to define the function and later call it. Since your mistakes are so basic i really recommend to start with a tutorial to learn javascript. I can recommend Eloquent JavaScript:
to learn the basics of functions
to understand the basics about the Document-Object Model
So, I've got a string. The string contains html. I'm checking the string for 'name', if it doesn't have one I'm using sneaking one in there if it does I need to change what it is.
var myString = '<input id="accountUser_c967817c993e62b1de50e4f0401a03ae" type="hidden" value="c967817c993e62b1de50e4f0401a03ae" name="addRow[]"><div class="colors goldbluegreenorange"></div>';
if (myString.indexOf('name') == -1) {
myString = myString.substr(0,myString.indexOf('>')) + ' name="addRow[]"' + myString.substr(myString.indexOf('>'));
} else {
//get what's inside name's quotes and change it to removeRow[].
}
I've got jquery going on too, if that makes more sense than straight javascript.
Since you're using jQuery, why not create a jQuery element out of that string, so that we can use jQuery's beautiful API for this? It'll make it far less error-prone than raw string manipulation.
Here's some sample code:
var $element = $('<input id="accountUser_c967817c993e62b1de50e4f0401a03ae" type="hidden" value="c967817c993e62b1de50e4f0401a03ae" name="addRow[]"><div class="colors goldbluegreenorange"></div>');
$element.filter('input').prop('name', function(i, v) {
return v ? 'removeRow[]' : 'addRow[]';
});
Note: the v in that function is the current value of the name attribute, which jQuery automatically passes in to the callback function. The return value is what the value of the attribute should be updated to.
Update: If you then want to convert it all back into a string, use this:
var theHTMLstring = $element.wrapAll('<div>').parent().html();
Here's the fiddle: http://jsfiddle.net/kBF3c/
Try converting the string to a jQuery object and reading the parameter from that:
var myString = '<input id="accountUser_c967817c993e62b1de50e4f0401a03ae" type="hidden" value="c967817c993e62b1de50e4f0401a03ae" name="addRow[]"><div class="colors goldbluegreenorange"></div>';
var $input = $(myString).filter('input');
$input.attr('name') = ($input.attr('name') == "") ? 'addRow[]' : 'removeRow[]';
Since you're using jQuery anyways, why don't you just parse the string and treat the tags as HTML?
var html = $.parseXML(string);
$.each(html.find('*'),function()
{
if ($(this).attr('name'))
{
$(this).attr('name', 'addRow[]');
}
else
{
$(this).attr('name','removeRow[]');
}
});
And take things from there?
Why don't you just use jQuery's inbuilt functionality.
Demo here
// specify string representing input element
var str = '<input id="accountUser_c967817c993e62b1de50e4f0401a03ae" type="hidden" value="c967817c993e62b1de50e4f0401a03ae" name="addRow[]"><div class="colors goldbluegreenorange"></div>';
var els = $(str);
// create element
var el = $(els).filter("input");
if( $(el).prop("name") ) {
$(el).prop( "name", "removeRow[]" );
} else {
$(el).prop("name", "anynameyouwant");
}
I am guessing you need to add the the above elements to the DOM which you can do like so
$("#parentId").append( els );
You may try this
var str = '<input id="accountUser_c967817c993e62b1de50e4f0401a03ae" type="hidden" value="c967817c993e62b1de50e4f0401a03ae" name="addRow[]"><div class="colors goldbluegreenorange"></div>';
$(str).prop('name', (!$(str).prop('name') ? "addRow[]" : "removeRow[]"));
str=$('<div/>').html(obj).html(); // str contains new value
DEMO.
how can concatenate the set variable in a for loop to be use as name in an input to get the value?
<script>
var k=0;
var counter = 50;
for(k=0; k<=counter; k++){
var choices = $('input[name=choices'+ k]).val();
var choices = choices.replace(/\ /g, '%');
var choices_ = choices_ +";"+ choices;
}
alert(choices);
</script>
there are multiple input field namely choices1,choices2 and so on.
how can i get the value of those fields using for loop?
how can i concatenate the name choices and the variable k?
can you help me solve this problem??
You could always just iterate using a specialized attribute selector and .each():
var choices = $('input[name^="choices"]'), // name starts with "choices"
choices_val = [] // an array!
;
choices.each(function () {
choices_val.push($(this).val().replace(/\ /g, '%'));
});
alert(choices_val.join(';'));
It saves you the overhead (and headache) of having to pick out and mangle a specific attribute value (choices1, choices2, etc) and having to select it out via selector ('cause I'd think that selecting via $(this) is faster than $('input[name="choices1"]')).
You're declaring choices three times, which is invalid and will lead to many errors.
You use each in jQuery, it's identical as for loop.
Say for example you have this HTML:
<input type ="text" name="field1" value="Alpha" />
<input type ="text" name="field2" value="Bravo" />
<input type ="text" name="field3" value="Charlie" />
And here is the js file:
var k = 1;
$('input').each(function(e) {
alert('choices' + k + '=' + $(this).val());
k++;
});
Demo here. Hope it helps.
$('input[name=choices'+ k +']').val();
you just forget to put another + sign and single quote.
I think you missed 2 quotes and a +.
$('input[name=choices' + k + ']').val();
add quotes
var choices = $('input[name=choices'+ k + ']').val();
use css selector
$(".className").each(function(){
$(this).myFunction();
})
jQuery.fn.myFunction = function()
var choices = $(this).val();
var choices = choices.replace(/\ /g, '%');
var choices_ = choices_ +";"+ choices;
}