Dynamic fields JS value showing "undefined" - javascript

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

Related

Getting a Value from an Input Box and Assign it in a Variable using Javascript

Hi I'm just new to Javascript and I am trying to assign a value to a variable coming from the input box then access that variable in a loop. I have tried using document.getElementbyID('inputboxID').value; and document.getElementbyName('inputboxName').value; but it didn't work.
Here's my code:
<script>
var count = 0;
$(function(){
$('p#add_field').click(function() {
var num = document.getElementById('enfonum').value;
while (count < num) {
count +=1;
$('#container').append(
'<strong>Enforcer #'+count+'</strong><br/>'
+'<input id="field_ '+count+'"name="field[]'+'"type="text"/><br/>');
}
});
});
}
</script>
Here's the code for the input box:
<input type="text" id="enfonum" name="enfotxt"/>
and here's the code for the link that will trigger the script to be executed:
<p id="add_field">< a href="#"><span>» Add Enforcer</span></a></p>
You have to get value of enfonum input at run-time, not storing it at num var during initial page loading.
Here is the working sample with correct code:
var count = 0;
var num = document.getElementById('enfonum');
$('p#add_field').click(function () {
while (count < num.value) {
count += 1;
$('#container').append('<p><strong>Enforcer #' + count + '</strong><br/>'
+ '<input id="field_' + count + '" name="field[]' + ' "type="text"/><br/></p>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><input type="text" id="enfonum" name="enfotxt" /></p>
<p id="add_field"><span>» Add Enforcer</span></p>
<div id="container"></div>
The reason your code is not working, is simply that document.GetElementById does not exists, the correct syntax is document.getElementById.
Here's a jsfiddle with an example.
Good luck and good continuation,
Cheers !
Remove the extra } in the code, it will give you syntax error.
Tried it afterwards,the code works.
Syntax errors can break your javascript, it is wise to use plugins like firebug for firefox to fish out javascript errors.
Let me know if it works.

Pull first instance of input and add id via JS

I have to add an id to an element. An engine generates the HTML... I have no access to it. It generates random IDs as such:
<input id="5352Adkdie4929888a">
I want to grab the first instance of "<input id=" and replace the ID it has with
the ID it has + DatePicker.
Example:
<input id="5352Adkdie4929888a DatePicker">
How would I go about doing this?
My code so far:
function addID(){
var html= document.documentElement.innerHTML;
var start= '<input id="';
var end= '"'
var htmlIWant=html.substring(html.indexOf(start) + start.length), html.indexOf(end)-1 + 'DatePicker';
}
Am I on the right track? How do I actually replace the HTML? Thanks!
This is a pure javascript solution as per your requirements.
Assuming that your page will have many input tags and some of them will be without ID attribute below is a solution you can try.
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++)
{
if (elements[i].type == "text" && elements[i].hasAttribute("id"))
{
var id = elements[i].getAttribute("id");
elements[i].setAttribute("id", id + "10");
break;
}
}
Grab the first input inside the element using
$('input:first-child').attr('id','whateverIdName');
If you have to catch first input box that has id attribute, you should do :
$("input[id]")[0]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JavaScript get the value of input in a div

I want to get the value of an input in a div.
I've tried document.getElementById('id').getElementsByTagName('input') but somehow I can't get the value.
HTML:
<div id="ST_RTM1_352X-MESSAGE_TYPED01_TXT">
<input class="MobileEditDisabled ABLED" value="E" size="2" maxlength="2" type="text">
</div>
JS :
var getV = document.getElementById("ST_RTM1_352X-MESSAGE_TYPED01_TXT").getElementsByTagName('input');
alert(getV.value);
JSFiddle: http://jsfiddle.net/aldimeola1122/2aLn33hn/
Or be more clever:
var getV = document.querySelector("#ST_RTM1_352X-MESSAGE_TYPED01_TXT input");
alert(getV.value);
getV contains a collection of nodes. You need to get first element getV[0] or getV.item(0) and then do another operations.
.getElementsByTagName returns a collection - reference the index you want:
var getV = document.getElementById("ST_RTM1_352X-MESSAGE_TYPED01_TXT").getElementsByTagName('input')[0];
You forgot de position because getV will get a collention's nodes, use [0] to get the node:
var getV = document.getElementById("ST_RTM1_352X-MESSAGE_TYPED01_TXT").getElementsByTagName('input')[0];
DEMO LIVE
Just add [0] after getElementsByTagName('input').
A Solution...
Lets say it like this:
My Version takes the Div Element and searches for All Input child Elements.
It works ;)
var getV = document.getElementById("ST_RTM1_352X-
MESSAGE_TYPED01_TXT").getElementsByTagName('input');
alert("Inputelements in the Div:" +getV.length);
for (var i = 0; i<getV.length; i++){
alert("Value of input " + i + ": " + getV[i].value);
}

how can concatenate the set variable in a for loop to be use as name in an input to get the value?

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;
}

Get array of values from multiple inputs using jQuery

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();
});
?

Categories

Resources