This question already has answers here:
how to store textbox values in array using jquery?
(2 answers)
Closed 8 years ago.
Here is my html input elements
<input type="text" name="pname[]" value="" />
<input type="text" name="pname[]" value="" />
<input type="text" name="pname[]" value="" />
<input type="text" name="pname[]" value="" />
<input type="text" name="pname[]" value="" />
<input type="text" name="pname[]" value="" />
How can I get all the values of pname array using Jquery
By Using map
var values = $("input[name='pname[]']")
.map(function(){return $(this).val();}).get();
You can use .map().
Pass each element in the current matched set through a function, producing a new jQuery object containing the return value.
As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.
Use
var arr = $('input[name="pname[]"]').map(function () {
return this.value; // $(this).val()
}).get();
Use:
function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
alert("pname["+i+"].value="+inp.value);
}
}
Here is Demo.
Related
Consider the following pairs of inputs
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
The number of pairs of inputs on a page is dynamic, not fixed.
I wish to loop through all pairs and store values as pairs to be output later into a table for example.
I've been trying to do it with jQuery's each() but I can't figure it out fully.
var detail = [];
//var detail = {};
$('input').each(function(index) {
detail[index] = $(this).val();
//detail.index = $(this).val();
});
console.log(detail);
This outputs
["iphone", "10", "macbook", "5"]
And it's not what I need.
I'm used to PHP, so what is the correct approach in JS/jQuery to store the pairs of inputs as a multidimensional associative array/object?
You can iterate over the elements with class item_name and create an array of objects that each have a name and qty property.
You can create this array more easily using jQuery's .map():
var details = $('.item_name').map(function() {
return {
name: $(this).val(),
qty: $(this).next('.item_qty').val()
};
}).get();
console.log(details);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
The equivalent of an associative array in javascript is an object (both act as a dictionary)
The problem you have is that your html describes a key and a value as inputs in a flat list, so when you enumerate them with your JQuery .each() you get them back all in one list.
[key, value, key, value]
what you most likely want is an object like:
var obj = {
key: value,
key: value
}
Then you can get at say the 'macbook' property like so
obj.macbook or obj['macbook']
You can achieve this by either looping through the list two at a time and adding them to the object, or by restructing your html to have both the key and value inputs inside another element e.g.
<div class="item">
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
</div>
<div class="item">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
</div>
Then you can do something like this:
var items = {}
$('.item').each(function(){
var key = $(this).find('.item_name').val()
var value = $(this).find('.item_qty').val()
items[key] = value;
})
var val = $("input.item_name").map(function(){
obj = {}
obj[$(this).val()] = $(this).next("input.item_qty").val();
return obj;
}).get()
console.log(val)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
Use .map()
You can use recursion, Array.prototype.slice() to slice two <input> elements at each function call, populate an object with key, value pairs until <input> elemnents .length is reached
var [obj, n] = [{}, 2];
var inputs = $("input[type=text]");
var res = (function re(i) {
if (i + n <= inputs.length) {
var [key, prop] = Array.from(inputs).slice(i, i + n).map(({value}) => value)
obj[key] = prop;
i += n;
return re(i)
} else {
return obj
}
})(0);
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
You can try a quick and "dirty" solution:
Ref: for each input type get value with javascript
You were on the right track with .getElementById, but you want instead, .getElementsByName.
var els = document.getElementsByName("filter[]");
for (var i = 0; i < els.length; i++)
alert(els[i].value);
<input id="filter_15" type="checkbox" name="filter[]" value="15">
<input id="filter_16" type="checkbox" name="filter[]" value="16">
<input id="filter_17" type="checkbox" name="filter[]" value="17">
Or, follow this: jQuery .each() with input elements
To extract number :
var arrNumber = new Array();
$('input[type=number]').each(function(){
arrNumber.push($(this).val());
})
To extract text:
var arrText= new Array();
$('input[type=text]').each(function(){
arrText.push($(this).val());
})
Edit : .map implementation
var arrText= $('input[type=text]').map(function(){
return this.value;
}).get();
I have array element in HTML
<input type="checkbox" value="Value1" name="model[settings][]">
<input type="checkbox" value="Value2" name="model[settings][]">
<input type="checkbox" value="Value3" name="model[settings][]">
I am reading all the HTML input, iterating it and building a hash in the javascript. But this will read the array element and only pick the last model[settings][] element.
var inputs = jQuery(" :input", "#elementID");
Is there a way in jQuery or JavaScript to read and build an array variable in javascript which then can be passed to controller ?
Thank You
If I understand you correctly, you are trying to iterate through all your input elements to get their value and store that as a JS object, correct?
If that's the case, I would add a unique ID to all my inputs, and then create an object with the structure { id : value }:
function getInputObject(sel) {
sel = $(sel);
var out = {};
sel.each(function() {
out[$(this).attr("id")] = $(this).val();
});
return out;
}
$(document).ready(function() {
console.log( getInputObject("input") );
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input1" value="value input 1" type="text" />
<input id="input2" value="value input 2" type="text" />
<input id="input3" value="value input 3" type="text" />
I have the following code:
<form>
<input type="text" id="field1" name="field1" value="first value" />
<input type="text" id="field2" onkeyup="showRSS(this.value, this.alt)" value="" alt="test">
</form>
Within the showRSS() onkeyup function I need to call the value from the first input field (id="field1"). How can I do that?
Use its ID with document.getElementById():
So if you want to pass it as the third argument to showRSS():
<input type="text" id="field2" onkeyup="showRSS(this.value, this.alt, document.getElementById('field1').value)" value="" alt="test">
Or if you want to get it from within showRss():
function showRSS( ... )
{
var field1 = document.getElementById('field1').value;
}
If you want to get the values of specific text boxes you can just iterate them in the function and grab the value of those you want based on their name. First, add a name to the second textbox as well then have such code:
function showRSS() {
var oForm = document.forms[0]; //assuming only one form
var desiredInputNames = { "field1": "", "field2": "" }; //names of elements to read
for (var i = 0; i < oForm.elements.length; i++) {
var element = oForm.elements[i];
if (desiredInputNames[element.name]) {
var value = element.value;
//handle the current value
}
}
}
(Using associative array rather than plain array for better searching)
use the below code to do that...
<form>
<input type="text" id="field1" name="field1" value="first value" />
<input type="text" id="field2" onkeyup="showRSS(this.value, this.alt, this.parentNode.getElementsByName('field1')[0].value)" value="" alt="test">
</form>
if you use field1 as name outside the form tag, it won't create any problem...
I am using a jquery template to dynamically generate multiple elements on the same page. Each element looks like this
<div id ="DynamicValueAssignedHere">
<div class="something">Hello world</div>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="FirstName" />
<input type="submit" value="Submit" />
</form>
</div>
</div>
I would like to use Jquery to process the form on submit. I would also like to revert the form values to their previous values if something should go wrong. My question is
How can I get the value of input box using Jquery? For example, I can get the value of the div with class "something" by doing
var something = $(#DynamicValueAssignedHere).children(".something").html();
In a similar fashion, I want to be able to retrieve the value of the textbox. Right now, I tried
var text = $(#DynamicValueAssignedHere).children(".formdiv").findnext('input[name="FirstName"]').val();
but it doesn't seem to be working
You have to use value attribute to get its value
<input type="text" name="FirstName" value="First Name" />
try -
var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();
It can be much simpler than what you are doing.
HTML:
<input id="myField" type="text" name="email"/>
JavaScript:
// getting the value
var email = $("#myField").val();
// setting the value
$("#myField").val( "new value here" );
An alternative approach, without searching for the field html:
var $form = $('#' + DynamicValueAssignedHere).find('form');
var formData = $form.serializeArray();
var myFieldName = 'FirstName';
var myFieldFilter = function (field) {
return field.name == myFieldName;
}
var value = formData.filter(myFieldFilter)[0].value;
$("form").submit(function(event) {
var firstfield_value = event.currentTarget[0].value;
var secondfield_value = event.currentTarget[1].value;
alert(firstfield_value);
alert(secondfield_value);
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" >
<input type="text" name="field1" value="value1">
<input type="text" name="field2" value="value2">
</form>
if you know the id of the inputs you only need to use this:
var value = $("#inputID").val();
var textValue = $("input[type=text]").val()
this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form
$('form[name=form1] input[type=text]')
Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.
You can try these lines:
$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value
You can get any input field value by
$('input[fieldAttribute=value]').val()
here is an example
displayValue = () => {
// you can get the value by name attribute like this
console.log('value of firstname : ' + $('input[name=firstName]').val());
// if there is the id as lastname
console.log('value of lastname by id : ' + $('#lastName').val());
// get value of carType from placeholder
console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="firstName" placeholder='first name'/>
<input type="text" name="lastName" id='lastName' placeholder='last name'/>
<input type="text" placeholder="carType" />
<input type="button" value="display value" onclick='displayValue()'/>
</form>
</div>
I have three input boxes, of which two are for entering values (any number) and one is for getting results (the difference of the two). How can I get the result without using page submission using Codeigniter?
You can use jQuery for that.
<input type="text" id=first" name="firstInput" />
<input type="text" id="second" name="secondInput" />
<input type="text" id="third" name="thirdInput" />
//jquery
$(document).ready(function() {
var first = parseInt($("#first").val(), 10);
var second = parseInt($("#second").val(), 10);
var thirdVal = first - second;
$("#third").val('');
$("#third").val(thirdVal);
});
Hope it helps
without exactly knowing how the result is being called you could use on onblur on the second number input/ first.
<input name="number" id="num_0" type="text" />
<input name="number" id="num_1" type="text" onblur="getResult()" />
<input name="number" id="num_2_result" type="text" />
script to get result derived for num_0 and num_1
function getResult(){
var number = document.getElementsByName('number');
var result = parseInt(number[0].value,10) - parseInt(number[1].value,10);
// if is a number display reuslt
if(!isNaN(result)){
number[2].value = result;
}
}