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" />
Related
I have an element in my page:
<form>
<div data-id="x">
<label>field 1</label>
<input name="field1" type="text" value="Foo" />
<label>field 2</label>
<input name="field2" type="number" value="5" />
</div>
<div data-id="y">
<label>field 1</label>
<input name="field1" type="text" value="Foo" />
<label>field 2</label>
<input name="field2" type="number" value="5" />
</div>
...other 100 inputs...
</form>
I'm looking for a javascript script like that:
var theElement = document.querySelector('[data-id="x"]');
var myObject = theElement.toObject();
And the object must looks like
{"field1":"Foo","field2":5}
I can't use the FormData strategy because I need a very small set of data from a very big form, but it is like a "partial FormData".
I'm asking if exists a standard method to convert the content of an HTMLElement in an object like for the FormData.
PS: i can use also the data-attribute if necessary
Actually there is no standard quicky method to do this task.
The solution is iterate over inputs and selects:
<script>
let myObj = {};
let element = document.querySelector('[data-id="x"]');
element.querySelectorAll('input').forEach(el=> {
// check the type
// the property is : el.name
// the value must be : el.value for text/number/email...
// the value for the type="checkbox" is according to checked attribute
});
element.querySelectorAll('select').forEach(sel=> {
// if multiple choise => create an array of selected options
// if single => check the selected option's value
});
</script>
This is the code i've used (simplified)
So I'm having trouble with JS and how to correctly collect and pass all values from a text field and hidden field on a button click.
<input autocomplete="off" id="add_109_01000340002001010_id" name="add_109_01000340002001010[id]" type="hidden" value="113000674">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001010_name" name="add_109_01000340002001010[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
<input autocomplete="off" id="add_109_01000340002001009_id" name="add_109_01000340002001009[id]" type="hidden" value="112000674">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001009_name" name="add_109_01000340002001009[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
<input autocomplete="off" id="add_109_01000340002001021_id" name="add_109_01000340002001021[id]" type="hidden" value="11405181">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001021_name" name="add_109_01000340002001021[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
Those are text fields and hidden fields with unique ids. They are 'connected'. When you change the value in the text field, the value in the hidden field changes automatically.
When you click on a button, then values that will be written in the text field should be processed in js
function room_group() {
$('.add').bind('click', function() {
var hidden_values = 'something here' // Let's get all values here and pass them to the get request
var values = 'something here' // Let's get all values here and pass them to the get request
$.post('/link/definition', {
val: values,
hidden_val: hidden_values
},
function(response) {
location.reload();
}
);
});
}
The question is how to collect all of those values correctly? Unfortunately, I have no idea...
It depends on how you want to format your values.
You can serialize the values by searching for them with an appropriate selector and then you can create a JSON string as value.
var hiddenValues = JSON.stringify($("input[type='hidden']").serializeArray());
var textValues = JSON.stringify($("input[type='text']").serializeArray());
console.log(hiddenValues);
console.log(textValues);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" value="h1" name="hidden1" />
<input type="hidden" value="h2" name="hidden2" />
<input type="text" value="t1" name="text1" />
<input type="text" value="t2" name="text2" />
Your POST will be something similar to:
var hiddenValues = JSON.stringify($("input[type='hidden']").serializeArray());
var textValues = JSON.stringify($("input[type='text']").serializeArray());
$.post('/link/definition', {
val: textValues,
hidden_val: hiddenValues
},
function(response) {
location.reload();
}
);
I just want to get all different values using javascript with the same id.
Here is my input code:
<input type="text" id="full" name="full" value="2018-12-06">
<input type="text" id="full" name="full" value="2018-12-14">
<input type="text" id="full" name="full" value="2018-12-18">
When I alert the id of the inputs it show's the 2018-12-06 only. I want to disable the jquery datepicker but the 2018-12-06 is the only one read.
Here is my calendar.
and my javascript code:
var x = (document.getElementById('full').value);
var array = ["2018-12-25", "2019-01-01", x]
I want to disable all value with same id like the mention above,
IDs must be unique. You should add a class to each element and then use getElementsByClassName.
Because the method returns a nodelist to get each input value you need to iterate over it. For both these examples I've used map, but you might find a for/loop or forEach easier to use.
const full = document.getElementsByClassName('full');
const arr = [...full].map(input => input.value);
console.log(arr);
<input type="text" class="full" value="2018-12-06">
<input type="text" class="full" value="2018-12-14">
<input type="text" class="full" value="2018-12-18">
An alternative might be to use querySelectorAll. This uses CSS selectors so you can pinpoint elements by their attributes instead:
const full = document.querySelectorAll('[name="full"]');
const arr = [...full].map(input => input.value);
console.log(arr);
<input type="text" name="full" value="2018-12-06">
<input type="text" name="full" value="2018-12-14">
<input type="text" name="full" value="2018-12-18">
ID is used as an individual identifier. So it is illegal to use same Id for multiple elements. To get values of multiple elements use class instead of id.
You can use getElementsByClassName() function to read values of all elements with same class name
Alternative to getElementsByClassName() using jQuery
var l = $('.full').length;
//Initialize default array
var result = [];
for (i = 0; i < l; i++) {
//Push each element to the array
result.push($('.full').eq(i).val());
}
//print the array or use it for your further logic
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="full" value="2018-12-06">
<input type="text" class="full" value="2018-12-14">
<input type="text" class="full" value="2018-12-18">
You can't create an element with the same Id, If you want to get all different values from another element using javascript you can use ClassName
<input type="text" class="full" name="full" value="2018-12-06">
<input type="text" class="full" name="full" value="2018-12-14">
<input type="text" class="full" name="full" value="2018-12-18">
var x = document.getElementsByClassName('full');
I have a website where there are five checkboxes, a div that contains another divs which each div contains five input hidden that have a value 1 or empty. That value comes from DB.
That's an example to represent the div container with the divs:
<input checkbox value="a">
<input checkbox value="b">
<input checkbox value="c">
<input checkbox value="d">
<input checkbox value="e">
<div class="container">
<div class="content" data-name="combine">
<input type="hidden" value="" data-name="a" />
<input type="hidden" value="" data-name="b" />
<input type="hidden" value="" data-name="c" />
<input type="hidden" value="" data-name="d" />
<input type="hidden" value="" data-name="e" />
</div>
<div class="content" data-name="combine">
<input type="hidden" value="1" data-name="a" />
<input type="hidden" value="" data-name="b" />
<input type="hidden" value="" data-name="c" />
<input type="hidden" value="1" data-name="d" />
<input type="hidden" value="" data-name="e" />
</div>
</div>
In the javascript code i have this snippet:
if(elementLength > 0) {
$("[data-name='combine'] div.tagsProds").each(function() {
var element = $(this);
$.each(enabledChecks,function(i, v) {
if(element.find("input[name='"+v+"']").val() == "") {
element.append("<div class='blocked'></div>");
element.unbind("click");
element.addClass("js_noSortable");
}
});
});
}
The javascript first checks if the div.container has childs and if it has childs the code iterates each child. On each child i iterate the five each checkbox (enabledChecks) and i see if the input hidden are empty. What i need if that if the five input are empty then append the `div.blocked'.
As i don't have enough reputation to write a comment i write an answer.
First, i think that your answer is quite interesting if you're looking to find a way using a jQuery function, but as i don't know any function to do this i think that you can create an array() and when you check if the input has empty value push it to the array, when the loop finishes you check the length of the array() and if it matches with the number of your checkboxes then append the .blocked
If I understand the question correctly, you want to find divs matching some selector that have no child input elements with non-empty values. The .filter method seems like a good fit here:
$("[data-name='"+name+"'] div.tagsProds")
.filter(function() {
// assert that at least one child input has a value
var $inputsWithValue = $(this).find("input[name='avail_" + v + "'][value!='']");
return $inputsWithValue.length === 0;
})
.each(function() {
// now act on those value-less divs
$(this)
.append("<div class='blocked'></div>")
.addClass("js_noSortable")
.unbind("click");
});
Another selector-only option might look like:
$("[data-name='"+name+"'] div.tagsProds:not(:has(input[name='avail_" + v + "'][value!='']))")
.each(function() {
// now act on those value-less divs
$(this)
.append("<div class='blocked'></div>")
.addClass("js_noSortable")
.unbind("click");
});
JSFiddle: http://jsfiddle.net/nrabinowitz/vrx2wk8g/
Note that the examples above follow the selectors in your sample code, but won't work against your sample markup.
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...