I have several select tags with different values of name attribute. I must get each of the value and put it into object variable. How to do it?
My code:
var obj = {};
$('.variants tbody tr td.value').children('select').each(function(index, value) {
alert($(this).attr('name'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="variants">
<tbody>
<tr>
<td>1</td>
<td class="value">
<select name="color">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
</tr>
<tr>
<td>2</td>
<td class="value">
<select name="size">
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</td>
</tr>
<tr>
<td>3</td>
<td class="value">
<select name="material">
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</td>
</tr>
</tbody>
</table>
Here, I must get
{"color":"selected_option_value", "size":"selected_option_value", "material":"selected_option_value"}
You should select all select elements in the table (you don’t need such a complex jQuery query to achieve so), iterate thru the collection; then for each element of the collection get its name (using the attr() function) and selected value (using the val() function) and create a property on the output object (obj) using the name of the select and assign its value to the select value.
// define the container object
var obj = {};
// for each select in the table
$('.variants select').each(function(index, select) {
// set the current item as a jQuery object
var current = $(select);
// sets the object key using the name of the select and the current selected value as the object key value
obj[current.attr('name')] = current.val();
});
// output
console.log(obj);
You could do the same using vanilla JavaScript too as in the other answers examples.
You can loop through the selection inputs with a forEach loop and fill in the obj object:
Select the input boxes and unwrap them in an array:
[...document.querySelectorAll('.value')]
in the loop select the child select element with:
menu.querySelector('select')
then add a new key/value pair in obj:
obj[element.getAttribute('name')] = element.value
↑ ↑
key value
So the full code looks like:
const obj = {}
document.querySelector('.button').addEventListener('click', (e) => {
[...document.querySelectorAll('.value')].forEach(menu => {
const element = menu.querySelector('select');
obj[element.getAttribute('name')] = element.value
})
console.log(obj)
})
I have set an event listener to show it working:
const obj = {}
document.querySelector('.button').addEventListener('click', (e) => {
[...document.querySelectorAll('.value')].forEach(menu => {
const element = menu.querySelector('select');
obj[element.getAttribute('name')] = element.value
})
console.log(obj)
})
<table class="variants">
<tbody>
<tr>
<td>1</td>
<td class="value">
<select name="color">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
</tr>
<tr>
<td>2</td>
<td class="value">
<select name="size">
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</td>
</tr>
<tr>
<td>3</td>
<td class="value">
<select name="material">
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</td>
</tr>
</tbody>
</table>
<button class="button">Give object</button>
You don't need jQuery to do this you, this will return an object on page load. You will have to wrap this in a function and add an event listener to return an object when the select values have changed or on form submission if thats what you are trying to accomplish
const variantsTable = document.querySelector('.variants')
const variantsSelects = Array.from(variantsTable.querySelectorAll('select'))
const obj = {}
variantsSelects.forEach(item => {
obj[item.name] = item.value
})
console.log(obj)
Output :
{"color":"1","size":"4","material":"7"}
You can try here :
const obj = {};
$('table.variants td.value select').each(function(index) {
obj[$(this).attr("name")] = $(this).val();
});
$("#output").text(JSON.stringify(obj));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="variants">
<tbody>
<tr>
<td>1</td>
<td class="value">
<select name="color">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
</tr>
<tr>
<td>2</td>
<td class="value">
<select name="size">
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</td>
</tr>
<tr>
<td>3</td>
<td class="value">
<select name="material">
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</td>
</tr>
</tbody>
</table>
<pre id="output"></pre>
Related
function extractTable() {
var csvTable = document.querySelector("#csv_table");
var newTableObj = [];
var tableRows = [].reduce.call(csvTable.rows, function(res, row) {
res[row.cells[0].textContent] = row.cells[1].textContent;
return res
}, {});
delete tableRows['Column value']; // Removes the header row
// Create an object
newTableObj.push(tableRows);
console.log(newTableObj);
// Create a JSON
let jsonTable = JSON.stringify(tableRows, null, 2);
console.log(jsonTable);
};
<table id="csv_table" class="sms_table">
<thead>
<tr>
<th>Column value</th>
<th>Field</th>
</tr>
</thead>
<tbody>
<tr>
<td>Name</td>
<td>
<select id="select_path" class="field_select">
<option selected="selected" value="">Please assign a Field</option>
<option value="a">A</option>
<option value="b">B</option>
</select>
</td>
</tr>
<tr>
<td>Prefix</td>
<td>
<select id="select_path" class="field_select">
<option selected="selected" value="">Please assign a Field</option>
<option value="a">A</option>
<option value="b">B</option>
</select>
</td>
</tr>
<tr>
<td>First</td>
<td>
<select id="select_path" class="field_select">
<option selected="selected" value="">Please assign a Field</option>
<option value="a">A</option>
<option value="b">B</option>
</select>
</td>
</tr>
<tr>
<td>Last</td>
<td>
<select id="select_path" class="field_select">
<option selected="selected" value="">Please assign a Field</option>
<option value="a">A</option>
<option value="b">B</option>
</select>
</td>
</tr>
</tbody>
</table>
<button id="extractTable" onclick="extractTable()">Extract table</button>
I have a simple two column table which is generated based upon the results of a parsed CSV file. The left column contains all of the values extracted, and the right column are a series of dropdowns which people can select a value.
I have some code which runs through the rows and extracts the values, which then I can drop into a multidimensional array or JSON.
I would like to be able to store these for use elsewhere but seem completely unable to extract the values of the dropdown field. Can anyone please help me?
My HTML table is something like this:
<table id="csv_table" class="sms_table">
<thead>
<tr>
<th>Column value</th>
<th>Field</th>
</tr>
</thead>
<tbody>
<tr>
<td>Name</td>
<td>
<select id="select_path" class="field_select">
<option selected="selected" value="">Please assign a Field</option>
<option value="a">A</option>
<option value="b">B</option>
</select>
</td>
</tr>
<tr>
<td>Prefix</td>
<td>
<select id="select_path" class="field_select">
<option selected="selected" value="">Please assign a Field</option>
<option value="a">A</option>
<option value="b">B</option>
</select>
</td>
</tr>
</tbody>
</table>
<button id="extractTable" onclick="extractTable()">Extract table</button>
My Js is:
function extractTable() {
var csvTable = document.querySelector("#csv_table");
var newTableObj = [];
var tableRows = [].reduce.call(csvTable.rows, function(res, row) {
res[row.cells[0].textContent] = row.cells[1].textContent;
return res
}, {});
delete tableRows['Column value']; // Removes the header row
// Create an object
newTableObj.push(tableRows);
console.log(newTableObj);
// Create a JSON
let jsonTable = JSON.stringify(tableRows, null, 2);
console.log(jsonTable);
};
My example codepen is here: https://codepen.io/AllenT871/pen/XoazJz?editors=1011#
I appreciate any help you can provide.
Instead of getting all the table you could get only the selectors using document.getElementsByClassName o document.getElementsByTagName
Then you can iterate (but its NOT an iterable you cannot use map or reduce) and get the selected value of every select.
I hope it helps
All code:
function extractTable() {
var tableItems = document.getElementsByClassName("field_select");
var tableRows = [];
for(var i = 0; i<tableItems.length; i++){
var e = tableItems[i]
var option = e.options[e.selectedIndex].value;
console.log(option)
tableRows.push(option);
}
// Create a JSON
let jsonTable = JSON.stringify(tableRows, null, 2);
console.log(jsonTable);
};
I want to create a drop down after user clicks on a table row.How can i do this using bootstrap and JavaScript?
Here is My table
jQuery(document).ready(function($) {
$(".clickable-row").click(function(e) {
if(e.target.id != "listItems"){
$(this).find("#listItems").toggle();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>
<table>
<tr class='clickable-row' data-href='url://'>
<td>1</td>
<td>ABC</td>
<td>123456789</td>
<td>
<select id="listItems">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
</tr>
<tr class='clickable-row' data-href='url://'>
<td>2</td>
<td>BCD</td>
<td>123456789</td>
<td>
<select id="listItems">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
</tr>
</table>
Following is my html code which is generated by php while loop :
<select class="menu_extra_item">
<option>--Qnt--</option>
<option>1</option>
<option>2</option>
<option>2</option>
</select>
<select class="menu_extra_item"/>
<option>--Qnt--</option>
<option>1</option>
<option>2</option>
<option>2</option>
</select>
<tr class="menu_extra_item_change">
<td>$32</td>
</tr>
<tr class="menu_extra_item_change">
<td>$10</td>
</tr>
I want to change the value (price like $32) when select option is change.
For e.g.
I select (first select) option `1`then it will be show `$32`
I select (first select) option `2`then it will be show `$62`
I select (second select) option `1`then it will be show `$10`
I select (second select) option `2`then it will be show `$20`
To get this output I am using following jQuery code but it's not working exactly what I want :(
jQuery code :
$(".menu_extra_item").each(function() {
$(this).change(function() {
var menu_extra_item =$(this).val();
var menu_extra_item_change = parseInt($('.menu_extra_item_change').text().replace(/[^0-9.]/g, ""));
alert(menu_extra_item_change);
var total_ex_price = menu_extra_item * menu_extra_item_change;
$(".menu_extra_item_change").each(function() {
$(".menu_extra_item_change").text("$"+total_ex_price);
});
});
});
You can also try this:
var prices = [32,10];
$("body").on("change",".menu_extra_item",function() {
var selInd = $(this).index() - 1;
var newVal = prices[selInd] * $(this).val();
$(".menu_extra_item_change").eq(selInd).text("$" + newVal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="menu_extra_item">
<option>--Qnt--</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select class="menu_extra_item">
<option>--Qnt--</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<table>
<tr class="menu_extra_item_change">
<td>$32</td>
</tr>
<tr class="menu_extra_item_change">
<td>$10</td>
</tr>
</table>
I corrected the faulty HTML, added data attribute to "link" each select to its corresponding price.
I also added a cell for total price, because each time the selection is made the price is multiplied from the value in the cell: so it continue to increase giving a bad result.
Here is a working solution:
$(document).ready(function(){
$(".menu_extra_item").on("change", function() {
var priceid = $(this).data("priceid");
var qty = parseInt($(this).val());
var price = parseInt($("#" + priceid).text().replace(/[^0-9.]/g, ""));
var total_ex_price = price * qty;
$("#total" + priceid).text("$"+total_ex_price);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="menu_extra_item" data-priceid="price1">
<option>--Qnt--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="menu_extra_item" data-priceid="price2">
<option>--Qnt--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<table>
<tr class="menu_extra_item_change">
<td>Unit price</td>
<td id="price1">$32</td>
<td>Total</td>
<td id="totalprice1">$32</td>
</tr>
<tr class="menu_extra_item_change">
<td>Unit price</td>
<td id="price2">$10</td>
<td>Total</td>
<td id="totalprice2">$10</td>
</tr>
</table>
You can do that by using data attributes. Check here
https://jsfiddle.net/v6qmhw77/
<select class="change-me" data-price="32" data-target=".element-1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="change-me" data-price="10" data-target=".element-2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div class="element-1"></div>
<div class="element-2"></div>
jQuery(document).ready(function(){
$('.change-me').change(function(){
var target = $(this).data('target');
var price = $(this).data('price');
var cost = parseInt(price) * $(this).val();
$(target).html("$"+cost);
});
});
That's easy.
$(".menu_extra_item").change(function() {
var multiplier = +$(this).val() || 1;
$(".menu_extra_item_change td").text(function() {
var baseValue = +$(this).data("baseValue");
return "$" + (multiplier * baseValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="menu_extra_item">
<option>Qnt</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<table>
<tr class="menu_extra_item_change">
<td data-base-value="32">$32</td>
</tr>
<tr class="menu_extra_item_change">
<td data-base-value="10">$10</td>
</tr>
</table>
This is not right way but If you want to go what you already have then follow this.
JsFiddle: https://jsfiddle.net/syjuLyh8/1/
<select class="menu_extra_item">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="menu_extra_item">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<table>
<tr class="menu_extra_item_change">
<td>$32</td>
</tr>
<tr class="menu_extra_item_change">
<td>$10</td>
</tr>
</table>
JS:
$(".menu_extra_item").each(function(index) {
var menu_extra_item_change = parseInt($('.menu_extra_item_change td').eq(index).text().replace(/[^0-9.]/g,""));
$(this).change(function() {
var menu_extra_item = $(this).val();
var total_ex_price = menu_extra_item * menu_extra_item_change;
$(".menu_extra_item_change").eq(index).text("$" + total_ex_price);
});
});
I have a page that allows a user to select the order of how fields are displayed. The drop downs are dynamically created and you only have the number of options based on the number of fields there are.
For example, if there are 5 fields, you have options 1-5 to sort your fields by.
What I am trying to accomplish is when you select a number from the dropdown, it "Swaps" that number with whatever one previously held that spot.
If I changed Record 4 to 3, those two drop downs would now be swapped... if that makes sense.
In the example below, change one of the numeric dropdowns to another choice. The original choice that held that value is updated but the actual one you are changing doesn't get the new value.
JS Fiddle: https://jsfiddle.net/y7g155mh/4/
<table name="selectedFields" class="table table-condensed selectedFields">
<thead>
<tr>
<th class="small span1">
<input type="checkbox" id="checkAllSelected">
</th>
<th class="small">Field Name</th>
<th class="small">Sort Order</th>
<th class="small">Sort Type</th>
<th class="small">Display Order</th>
</tr>
</thead>
<tbody name="selectedRows">
<tr data-fid="5">
<td class="small"></td>
<td class="small">Request ID</td>
<td class="small">
<select data-current="1" data-type="sortOrder" class="span1" name="sortOrder">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td class="small">
<select class="span1" name="sortType">
<option value="-">-</option>
<option selected="selected" value="ASC">ASC</option>
<option value="DESC">DESC</option>
</select>
</td>
<td class="small">
<select data-current="1" data-type="displayOrder" class="span1" name="displayOrder">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
</tr>
<tr data-fid="16">
<td class="small"></td>
<td class="small">Task ID</td>
<td class="small">
<select data-current="2" data-type="sortOrder" class="span1" name="sortOrder">
<option value="1">1</option>
<option selected="selected" value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td class="small">
<select class="span1" name="sortType">
<option value="-">-</option>
<option selected="selected" value="ASC">ASC</option>
<option value="DESC">DESC</option>
</select>
</td>
<td class="small">
<select data-current="2" data-type="displayOrder" class="span1" name="displayOrder">
<option value="1">1</option>
<option selected="selected" value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
</tr>
<tr data-fid="9">
<td class="small"></td>
<td class="small">Task Start Date</td>
<td class="small">
<select data-current="3" data-type="sortOrder" class="span1" name="sortOrder">
<option value="1">1</option>
<option value="2">2</option>
<option selected="selected" value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td class="small">
<select class="span1" name="sortType">
<option value="-">-</option>
<option selected="selected" value="ASC">ASC</option>
<option value="DESC">DESC</option>
</select>
</td>
<td class="small">
<select data-current="3" data-type="displayOrder" class="span1" name="displayOrder">
<option value="1">1</option>
<option value="2">2</option>
<option selected="selected" value="3">3</option>
<option value="4">4</option>
</select>
</td>
</tr>
<tr data-fid="17">
<td class="small"></td>
<td class="small">Task Completion Date</td>
<td class="small">
<select data-current="4" data-type="sortOrder" class="span1" name="sortOrder">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option selected="selected" value="4">4</option>
</select>
</td>
<td class="small">
<select class="span1" name="sortType">
<option value="-">-</option>
<option selected="selected" value="ASC">ASC</option>
<option value="DESC">DESC</option>
</select>
</td>
<td class="small">
<select data-current="4" data-type="displayOrder" class="span1" name="displayOrder">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option selected="selected" value="4">4</option>
</select>
</td>
</tr>
</tbody>
</table>
$('body').on('change', 'select', function() {
saveOrder($(this).val(), $(this).data('type'), $(this).data('current'));
});
// Update the field order numbers and save the data
function saveOrder(order, type, current) {
// First thing we need to do is swap the selected value with the one we are changing it for.
$('[name=' + type + ']').find('option[value="' + order + '"]:selected').parent().val(current);
return false;
// Do something here with storing data
}
It seems like this is what you want to achieve. There is room for improvement.
$('body').on('change', 'select', function() {
saveOrder($(this));
});
// Update the field order numbers and save the data
function saveOrder(select) {
var order = select.val(),
type = select.data('type'),
current = select.data('current');
$('select[name=sortOrder][data-current="'+current+'"]').val(order);
$('select[name=sortOrder][data-current="'+order+'"]').val(current);
return false;
// Do something here with storing data
}
I wanted to create a table where dynamic values are displayed in a column depending on values selected by users. Below is my code for it. So basically, depending on the number of adults and number of children that are selected, the Price will be calculated. So if someone chooses 1 adult and 0 children, then the Amount for 2 Day ticket should be $235, for 3 day it will be $301 and so on. I want this done on selection change method of selectboxes. I am also not very familiar with JQuery. How do I accompalish this using JQuery?
Ages 10+:
<select id="Adult" name="Adult">
<option selected="selected" value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
Ages 3-9:
<select id="Child" name="Child">
<option selected="selected" value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<table width="800" border="1" align="center">
<tr>
<td width="224">Product</td>
<td width="246">Ages 10+</td>
<td width="192">Ages 3-9</td>
<td width="110">Price</td>
</tr>
<tr>
<td>2 Day Ticket</td>
<td>$235.00</td>
<td>$223.00</td>
<td>$<span class="amount"></span> </td>
</tr>
<tr>
<td>3 Day Ticket</td>
<td>$301.00</td>
<td>$285.00</td>
<td>$<span class="amount"></span></td>
</tr>
<tr>
<td>4 Day Ticket</td>
<td>$315.00</td>
<td>$298.00</td>
<td>$<span class="amount"></span></td>
</tr>
<tr>
<td>5 Day Ticket</td>
<td>$328.00</td>
<td>$309.00</td>
<td>$<span class="amount"></span></td>
</tr>
</table>
Here is complete code to accomplish what you're trying to do. I added some id's to the totals. See the fiddle for a working example. It would be better to not hard code the values, but this works as a starting point.
var numAdult = 0;
var numChild = 0;
$("#Adult").change( function(){
numAdult = $("#Adult").val();
calcTotals();
});
$("#Child").change( function() {
numChild = $("#Child").val();
calcTotals();
});
function calcTotals(){
$("#2DayTotal").text(235*numAdult + 223*numChild);
$("#3DayTotal").text(301*numAdult + 285*numChild);
$("#4DayTotal").text(315*numAdult + 298*numChild);
$("#5DayTotal").text(328*numAdult + 309*numChild);
}