Get ID of all child elements and its input/select data - javascript

How can I get the id of each child element and its tag name so I can save the data of each column to a string?
<div class="row">
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text">
</div>
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text">
</div>
<div class="col-md-4">
<select id="poz-3-s">
<option value="1">-Pick-</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
</div>
</div>
I've got the loop so far, but I don't know how to get the data depending on the input/select:
for (var j = 0; j < (nCols / nRows); j++) {
}

You could use .find('*') to get all the childs :
$('.row').find('*').each(function(){
//Get the id and value
})
Hope this helps.
$('.row').find('*').each(function(){
if($(this).prop('tagName')!='OPTION')
console.log("id = "+$(this).prop('id')+" / value = "+$(this).val());
else
console.log("id = "+$(this).prop('id')+" / value = "+$(this).text());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text" value='first input'>
</div>
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text" value='second input'>
</div>
<div class="col-md-4">
<select id="poz-3-s">
<option value="1">-Pick-</option>
<option value="2" selected>test2</option>
<option value="3">test3</option>
</select>
</div>
</div>

If I understood you correctly you can get all input's values simply by iterating through them with jQuery:
$.each($('.col input, .col select'), function(index, item) {
console.log('ELEMENT ID ' + $(item).attr('id') + ' VAL - ' + $(item).val());
});
of simply use serializeArray method like this:
$('input, select').serializeArray()
Working example of both ways here: https://jsfiddle.net/hc882g27/
P.S.: in pure javascript it could be done with querySelectorAll function:
var items = document.querySelectorAll('.col input, .col select');
for (var i = 0; i < items.length; i++) {
console.log(items[i].value);
}

Related

How to get option value of only the selected checkboxes?

I want to get option value of only selected checkbox, but I am getting value from all the checkboxes.
My HTML code:
<div class= "outer">
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane">BBQ Sauce<br>
<select class="weight" name="m2" id="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>
</div>
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane"> Alfredo Sauce<br>
<select class="weight" name="m2" id="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>
</div>
</div>
<input type="submit" value="Submit">
My JavaScript code:
function myAction(){
var vals = [];
var machine = document.getElementsByName('machine');
var m2 = document.getElementById('m2');
for(var i=0, n= machine.length; i<n; i++){
if(machine[i].checked){
vals.push(m2.value);
}
}
}
IDs must be unique.
Instead, you could use querySelectorAll() on the existing weight classes to grab only the select elements that follow a checked input (using the general sibling selector):
document.querySelectorAll('input:checked ~ .weight')
The select element values will be the same as their selected options' values.
Snippet
document.querySelector('input[type=submit]').addEventListener('click', myAction);
function myAction() {
var vals = [], //no need for new Array()
weights= document.querySelectorAll('input:checked ~ .weight');
for(var i = 0 ; i < weights.length ; i++) {
vals.push(weights[i].value);
}
console.log(vals);
}
<div class="outer">
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane">I have a plane
<br>
<select class="weight" name="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>
</div>
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane">I have 2 planes
<br>
<select class="weight" name="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>
</div>
</div>
<input type="submit" value="Submit">
You have m2 repeated twice in your code. HTML spec specifies undefined behavior when id is repeated (m2). Also your select box isn't a multi-select. You should just be able to get the value from the select box directly if that is the case.
You can use querySelector also on nested nodes,
so you could filter the div.inner blocks which have the input checked and then get the values from there:
function myAction() {
//var vals = new Array();
var inner = [].slice.call(document.querySelectorAll('.inner'));
var checked = inner.filter(function(x) {
var chk = x.querySelector('input');
if (chk.checked) return x;
})
var vals = checked.map(function(x){
var i = x.querySelector('select').value;
return i
});
}
BTW as Rick said your markup contain some errors so I would suggest to pass it through a validator_
for calling your function on click event of the input submit:
document.querySelector('input[type=submit').addEventListener('click', myAction)

Fill select list with values depending on preselection

I want to have one select list populated with different values (price) depending on which option was chosen in other select list (sale or rent)
So what I have done is first create the arrays for sale and rent.
Then get the jquery and do an change event to pick which selection was made.
then a Switch statement that should populate the select list in question, but it is not showing anything. While jquery is a library for javascript I dont know if mixing them like I have done is alright:
$('#transaction').change(function(){
$value = $('#transaction').val();
var sale = [];
for (var i = 350000; i <= 2000000; i+100000) {
sale.push(i);
}
var rent = [];
for (var i = 500; i <= 6000; i+100) {
rent.push(i);
}
switch($value) {
case 'sale':
$.each(sale, function(key, value){
$('#price').append('<option value="' + index+ '">' + value + '</option>')
break;
case 'rent':
break;
}); // end of each
} // end of switch
}) ; //end of jquery snippet
<div class="row">
<div class="col-md-2 col-md-offset-1">
<div class="form-group">
{{Form::label('transaction', 'Transaction')}}
<select name="transaction" id="transaction" class="form-control">
<option value="select">Select</option>
<option value="sale">Sale</option>
<option value="rent">Rent</option>
<option value="holiday">Holiday</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
{{Form::label('price', 'Price')}}
<select name="price" id="price" class="form-control">
</select>
</div>
</div>
You dont have the options element in your select tag, so it never gets the $value from this statement :- $value = ('#transaction').val();
Insert the option tags and then run your example.
All credits go to Keith Wood (Sydney)
$(function() {
$('#transaction').change(function() {
var sale = [];
for (var i = 350000; i <= 2000000; i += 100000) {
sale.push(i);
}
var rent = [];
for (var i = 500; i <= 6000; i += 100) {
rent.push(i);
}
var option = $('#transaction').val();
var prices = (option === '1' ? sale : (option === '2' ? rent : []));
var options = '';
$.each(prices, function(key, value) {
options += '<option value="' + value + '">' + value + '</option>';
});
$('#price').html(options);
});
});
<div class="col-md-2 col-md-offset-1">
<div class="form-group">
{{Form::label('street', 'Transaction')}}
<select name="transaction" id="transaction" class="form-control">
<option value="0">Select</option>
<option value="1">Sale</option>
<option value="2">Rent</option>
<option value="3">Holiday</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
{{Form::label('price', 'Price')}}
<select name="price" id="price" class="form-control">
</select>
</div>
</div>

javascript getElementById start with

I want to select div start with * to change it from display: block to display:hidden
function select_to_text(a) {
var as = '#' + a;
var aa = $(as).val();
if (aa == "0") {} else {
//var $eles = $(":*[name^='personal_family_type_']").css("background-color","yellow");
document.getElementById(a + "_" + aa + "_block").style.display = 'block';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="personal_family_type" class="control-label col-sm-2">type</label>
<div class="col-sm-10">
<select size="1" id="personal_family_type" name="personal_family_type" class="form-control btn btn-primary" onchange="select_to_text('personal_family_type')">
<option value="0">----</option>
<option value="wife">Wife</option>
<option value="husband">Husband</option>
<option value="son">Son</option>
<option value="all">Show all</option>
</select>
<div id="personal_family_type_wife_block" style="display :none">
wife
</div>
<div id="personal_family_type_husband_block" style="display :none">
husband
</div>
<div id="personal_family_type_son_block" style="display :none">
son
</div>
</div>
</div>
you should not pass in params to your onchange handler -- you can get more flexibility if you tap into the event callback stuff via javascript. I'd also utilize classes to find your elements of interest...there are ways to make the selector more efficient, but to illustrate the point, I'm keeping it simple.
to start -- replace some of the encoded information from the id of the divs with class names and remove the onchange property.
<div class="form-group">
<label for="personal_family_type" class="control-label col-sm-2">type</label>
<div class="col-sm-10">
<select size="1" id="personal_family_type" name="personal_family_type" class="form-control btn btn-primary" >
<option value="0">----</option>
<option value="wife">Wife</option>
<option value="husband">Husband</option>
<option value="son">Son</option>
<option value="all">Show all</option>
</select>
<div id="wife_block" class="personal_family_type" style="display :none">
wife
</div>
<div id="husband_block" class="personal_family_type" style="display :none">
husband
</div>
<div id="son_block" class="personal_family_type" style="display :none">
son
</div>
</div>
</div>
next, bind your select element to the onchange handler and then the logic in select_to_text, in a nutshell:
set all elements to display:none, then set the specific elements to display:block per the settings (I'm assuming I understand the way this is supposed to work).
script:
$('#personal_family_type').on('change',select_to_text);
function select_to_text(evt) {
var $blocks;
$blocks = $('.'+evt.target.id).hide();
switch (evt.target.value) {
case '0':
break;
case 'all':
$blocks.show();
break;
default:
$('#' + evt.target.value + "_block").show();
}
}
Here is a solution done in jQuery. Remove the onclick from your html element.
$( document ).ready(function() {
$('#personal_family_type').on('click', function() {
$("#"+this.id + "_" + this.value + "_block").toggle();
});
});
Here is a Demo
You should definitely use jQuery in this case. If I understand your question correctly, you could do something like this:
$("#personal_family_type option:selected").click(function() {
var family_select_option = $(this).val();
$('#personal_family_type_'+family_select_option+'block').show();
});
Given:
<select size="1" id="personal_family_type" name="personal_family_type"
class="form-control btn btn-primary"
onchange="select_to_text('personal_family_type')">
You can instead do:
<select size="1" name="personal_family_type"
class="form-control btn btn-primary"
onchange="select_to_text(this)">
then in the function:
// a is a reference to the element calling the function
function select_to_text(a) {
var aa = a.value;
then I think you want:
if (aa !== "0") {
var el = document.getElementById(a.name + '_' + aa + '_block');
// set display to empty string so adopts default or inherited style
if (el) el.style.display = '';
}
}
which can be reduced to:
function select_to_text(a) {
if (aa.value !== '0')
document.getElementById(a.name + '_' + aa.value + '_block'.style.display = '';
}

jquery append not working properly in my application

i have a javascript which is generating the below html dynamically. I want those two dropdowns for all list elemnts. Here it is happening only for last list element.
<ul id="drivernvehicle">
<li>
<div class="form-group" id="1"></div>1.</li>
<li>
<div class="form-group" id="2"></div>2.</li>
<li>
<div class="form-group" id="3"></div>3.</li>
<li>
<div class="form-group" id="4"></div>4.
<select class="form-control input-lg required">
<option value="M" selected="selected"><--select Driver--></option>
<option value="25">25</option>
</select>
<select class="form-control input-lg required">
<option value="N" selected="selected"><--select Vehicle--></option>
<option value="23">23</option>
</select>
</li>
</ul>
JS
$('#drivernvehicle').empty();
var i = $('#noOfVehicle').val();
var j;
var temp;
var items = [];
for (j = 0; j < i; j++) {
temp = j + 1;
//var selectDiv = selectDiv + temp;
var selectDiv = $("<li><div class=\"form-group\" id=\"" + temp + "\"></div></li>");
selectDiv.append(temp + ". ")
.append(driverSelectBox)
.append(vehicleSelectBox);
items.push(selectDiv);
}
$('ul#drivernvehicle').append(items);
javascript below which generate above html. here "driverSelectBox" and "vehicleSelectBox" are two dropdown which has been crated dynamically.
You need to have something to display.
Here's a jsFiddle: http://jsfiddle.net/t8jo77Le/
I hardcoded/deleted the stuff you failed to include.
I added the 'Hello' here:
$("<li><div class=\"form-group\" id=\"" + temp + "\">Hello</div></li>");
Without it, it doesn't display.

Javascript hide values depending on a selected option

I need help with some javascript. The idea is to hide some values from a depending on a parent
here is the html
<div class="form-group" style="margin-top: 20px;">
<label for="inputPassword3" class="col-sm-2 control-label">Phase</label>
<div class="col-sm-10">
<select class="form-control" name="phase" id="phase">
{%if phases is defined%}
{%for phase in phases%}
<option value="{{phase.id}}">{{phase.nom}}</option>
{%endfor%}
{%endif%}
</select>
</div>
</div>
<div class="form-group" >
<label for="inputPassword3" class="col-sm-2 control-label">Sous phase</label>
<div class="col-sm-10">
<select class="form-control" name="ssphase" id="ssphase">
{%if ssphases is defined%}
{%for ssphase in ssphases%}
<option value="{{ssphase.id}}" id="{{ssphase.phaseid}}">{{ssphase.nom}}</option>
{%endfor%}
{%endif%}
</select>
</div>
</div>
Do you have any idea to make the javascript hide options with the id that doesnt match with the value of the option selected on the first select?
Thanks for helping !
You can do it like this:
phase.onchange = function () {
show_sphases (this.value);
}
function show_sphases (phase) {
var subphases = document.querySelectorAll("[data-phase='" + phase + "']");
var allSubphases = document.querySelectorAll("#ssphase option");
for (var i = 0; i <= allSubphases.length; i++ ){
var item = allSubphases.item(i);
$(item).hide();
}
for (var i = 0; i <= subphases.length; i++ ){
var item = subphases.item(i);
$(item).show();
}
}
You also have to add a data-phase attribute to your ssphases options so that you can link them together, like this:
<option value="11" id="11" data-phase="1">Subphase #1-1</option>
I used jQuery for $().hide and $().show.
Here's a fiddle.

Categories

Resources