Get mondays dates based on selected month in javascript - javascript

This question is related to this SO question, and the provided solution is working fine. However, in my case, I want to get dates of mondays in a selected month from dropdown menu.
The code what I have tried is:
var d = new Date(),
month = d.getMonth(),
mondays = [],
mondaysChange = [];
//console.log("current month is: "+month);
//console.log("current months mondays are: " + getMondays());
$("#ddlMonths option").filter(function() {
return this.value == month;
}).attr('selected', true);
$('#ddlMonths').on('change', function(e) {
var m = $("option:selected", this).val();
console.log("selected month: " + m);
var str = getMondaysChange(m);
console.log("selected months mondays are: " + str);
});
function getMondaysChange(m) {
d.setDate(1);
d.setMonth(m);
console.log("you have selected: " + d + " month");
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === m) {
mondaysChange.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
return mondaysChange;
}
function getMondays() {
d.setDate(1);
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === month) {
mondays.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
return mondays;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.min.js"></script>
<div class="data-block">
<div class="data-container">
<header>
<h2>
Track</h2>
</header>
<div class="form-horizontal">
<div class="form-group">
<label for="CAASRTUserName" class="col-sm-2 control-label">Resource</label>
<div class="col-sm-10">
<input id="CAASRTUserName" type="text" data-bind="value: Vendor" placeholder="" class="form-control hasclear">
</div>
</div>
<div class="form-group has-feedback">
<label for="InvoiceTotal" class="col-sm-2 control-label">Enter for Month</label>
<div class="col-sm-10">
<select id="ddlMonths" class="form-control">
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select>
</div>
</div>
<!-- <div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="btnTrack" data-bind="click: Submit" class="btn btn-default">
Submit
</button>
</div>
</div> --></div>
<br>
<div class="row">
<div class="col-md-12">
<!-- <h4>
<span id="mySpanCur">Current Week</span>
</h4> -->
<div id="divtblTrack" class="plan">
<table id="tblTrack" class="table table-bordered">
<thead>
<tr>
<th>Parent Activity</th>
<th>Hrs/ Wk</th>
<th>Activity</th>
<th><span id="week1"></span>
</th>
<th><span id="week2"></span>
</th>
<th><span id="week3"></span>
</th>
<th><span id="week4"></span>
</th>
<th>Comments</th>
<th>Total</th>
<th style="display:none">PlanEntryId</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td id="HrsByWkSum">204</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td id="TotalSum">0</td>
<td style="display:none"></td>
</tr>
</tfoot>
<tbody>
<tr>
<td class="emptyTd"><span>Analytics</span>
</td>
<td class="hoursbyweek emptyTd"><span>67</span>
</td>
<td class="DD">
<select class="form-control" readonly="readonly">
<option value="Select">Select</option>
</select>
</td>
<td class="mon">
<input type="text" id="txtMon" class="form-control" style="width:40px;" value="" />
</td>
<td class="tue">
<input type="text" id="txtTue" class="form-control" style="width:40px;" value="" />
</td>
<td class="wed">
<input type="text" id="txtWed" class="form-control" style="width:40px;" value="" />
</td>
<td class="thu">
<input type="text" id="txtThu" class="form-control" style="width:40px;" value="">
</td>
<td>
<input type="text" id="txtComments" class="form-control" style="width:90px;" value="">
</td>
<td class="tot emptyTdTot"></td>
<td style="display:none">3</td>
<td>
<button class="btn btn-primary btn-xs myBtn">Add</button>
</td>
</tr>
<tr>
<td class="emptyTd"><span>General Admin</span>
</td>
<td class="hoursbyweek emptyTd"><span>36</span>
</td>
<td class="DD">
<select class="form-control" readonly="readonly">
<option value="Select">Select</option>
</select>
</td>
<td class="mon">
<input type="text" id="txtMon" class="form-control" style="width:40px;" value="">
</td>
<td class="tue">
<input type="text" id="txtTue" class="form-control" style="width:40px;" value="">
</td>
<td class="wed">
<input type="text" id="txtWed" class="form-control" style="width:40px;" value="">
</td>
<td class="thu">
<input type="text" id="txtThu" class="form-control" style="width:40px;" value="">
</td>
<td>
<input type="text" id="txtComments" class="form-control" style="width:90px;" value="">
</td>
<td class="tot emptyTdTot"></td>
<td style="display:none">2</td>
<td>
<button class="btn btn-primary btn-xs myBtn">Add</button>
</td>
</tr>
<tr>
<td class="emptyTd"><span>Reports</span>
</td>
<td class="hoursbyweek emptyTd"><span>56</span>
</td>
<td class="DD">
<select class="form-control" readonly="readonly">
<option value="Select">Select</option>
</select>
</td>
<td class="mon">
<input type="text" id="txtMon" class="form-control" style="width:40px;" value="">
</td>
<td class="tue">
<input type="text" id="txtTue" class="form-control" style="width:40px;" value="">
</td>
<td class="wed">
<input type="text" id="txtWed" class="form-control" style="width:40px;" value="">
</td>
<td class="thu">
<input type="text" id="txtThu" class="form-control" style="width:40px;" value="">
</td>
<td>
<input type="text" id="txtComments" class="form-control" style="width:90px;" value="">
</td>
<td class="tot emptyTdTot"></td>
<td style="display:none">6</td>
<td>
<button class="btn btn-primary btn-xs myBtn">Add</button>
</td>
</tr>
<tr>
<td class="emptyTd"><span>Time not working</span>
</td>
<td class="hoursbyweek emptyTd"><span>45</span>
</td>
<td class="DD">
<select class="form-control" readonly="readonly">
<option value="Select">Select</option>
</select>
</td>
<td class="mon">
<input type="text" id="txtMon" class="form-control" style="width:40px;" value="">
</td>
<td class="tue">
<input type="text" id="txtTue" class="form-control" style="width:40px;" value="">
</td>
<td class="wed">
<input type="text" id="txtWed" class="form-control" style="width:40px;" value="">
</td>
<td class="thu">
<input type="text" id="txtThu" class="form-control" style="width:40px;" value="">
</td>
<td>
<input type="text" id="txtComments" class="form-control" style="width:90px;" value="">
</td>
<td class="tot emptyTdTot"></td>
<td style="display:none">1</td>
<td>
<button class="btn btn-primary btn-xs myBtn">Add</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<div class="pull-right">
<button id="btnSubmit" data-bind="click: Submit" class="btn btn-default">Save</button>
</div>
</div>
</div>
</div>
<br>
</div>
</div>
Jsbin for the same is here. I am setting the month on change of dropdown and am still wondering why the mondaysChange array is returning empty. Can anyone check it?
A momentjs solution for the same also fine which I can't seem to get it easily.

for start of week use this
var startDay = 0;
var d =today.getDay();
var weekStart = new Date(today.valueOf() - (d<=0 ? 7-startDay:d-startDay)*86400000); //rewind to start day
var nextweekStart =new Date(weekStart.valueOf() + (7)*86400000);//get first day of next week
var prevweekStart =new Date(weekStart.valueOf() - (7)*86400000);//get first day of prev week
if startDay =0; return sunday then use 1 instead of 0 as:
//0=sunday, 1=monday etc.

Here's a more generic function to retrieve all dates for a certain day for a month from a given date. See the snippet, where it is used within the change handler of the selector.
function getAllInstancesOfDayInMonth(fordate, forday) {
fordate.setDate(1);
var start = getStartDay(fordate, forday)
,month = fordate.getMonth()
,result = [start];
while (fordate.getMonth() == month) {
result.push(new Date(fordate.setDate(fordate.getDate()+7)));
}
return result.slice(0,-1);
function getStartDay(d, forday) {
return d.getDay() != +forday
? ( d.setDate( d.getDate() + 1 ), getStartDay(d, forday) )
: new Date(d);
}
}
(function () {
document.querySelector('#ddlMonths')
.addEventListener('change', getMondays);
var result = document.querySelector('#result');
result.innerHTML = '<h3>all mondays in January 2015</h3>';
result.innerHTML += getAllInstancesOfDayInMonth(
new Date([2015,1,1].join('/')), 1
).join('\n');
function getMondays(e){
var year = this.getAttribute('data-year')
,month = +this.options[this.selectedIndex].value
,monthstr = this.options[this.selectedIndex].innerHTML;
result.innerHTML = '<h3>all mondays in '+monthstr+' '+ year+'</h3>';
result.innerHTML += getAllInstancesOfDayInMonth(
new Date([year,month+1,1].join('/')), 1
).join('\n');
}
function getAllInstancesOfDayInMonth(fordate, forday) {
fordate.setDate(1);
var start = getStartDay(fordate, forday)
,month = fordate.getMonth()
,result = [start];
while (fordate.getMonth() == month) {
result.push(new Date(fordate.setDate(fordate.getDate()+7)));
}
return result.slice(0,-1);
function getStartDay(d, forday) {
return d.getDay() != +forday
? ( d.setDate( d.getDate() + 1 ), getStartDay(d, forday) )
: new Date(d);
}
}
}())
body {font: 12px/15px normal verdana, arial; margin:1.5em; }
<select id="ddlMonths" class="form-control" data-year="2015">
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select> Select a month to retrieve all mondays of it
<pre id="result"></pre>

I think the problem is the comparison d.getMonth() === m, you are passing m as the selected option value which will be of type string where as d.getMonth() is a of type number.
so try
//empty the array
mondaysChange.length = 0;
//change the type of m to number
m = +m;
d.setDate(1);
d.setMonth(m);
console.log("you have selected: " + d + " month");
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === m) {
mondaysChange.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
Demo: Fiddle, Problem

Related

jQuery change other value if main input form is (on.change)

I am using Laravel and javascript + jQuery then, what I need is if I click the select option value, it will change the other form input based on (count value).
Here is my preview image :
nah if i click the value of select option in "Tipe Biaya" column, it will count jumlah column*biaya operational column then put the result in total column (in One row).
here my Html code:
<table class="table table-bordered table-responsive-md table-striped text-center">
<thead>
<tr>
<th class="text-center">Nama Cabang</th>
<th class="text-center">Jumlah</th>
<th class="text-center">Biaya Operasional</th>
<th class="text-center">Tipe Biaya</th>
<th class="text-center">Total</th>
</tr>
</thead>
<tbody class="distributionList">
#foreach($branches as $key => $fb)
<tr>
<td class="pt-3-half text-left">
{{ $fb->name }}
</td>
<td class="pt-3-half">
<input type="number" class="form-control product_quantity" name="product_quantity[{{$fb->id}}]" id="product_quantity" value="" placeholder="0">
</td>
<td class="pt-3-half">
<input type="number" class="form-control each_operational_cost" name="each_operational_cost[{{$fb->id}}]" id="each_operational_cost" value="" placeholder="0">
</td>
<td class="pt-3-half">
<select class="form-control operational_cost_type" name="operational_cost_type" id="operational_cost_type">
<option value="pecentage">Pecentage</option>
<option value="flat">Number</option>
</select>
</td>
<td class="pt-3-half">
<input type="text" class="form-control total_operational_cost" name="total_operational_cost[{{$fb->id}}]" id="total_operational_cost" value="" placeholder="0" readonly>
</td>
</tr>
#endforeach
</tbody>
</table>
Here my JavaScript and jQuery
$(document).ready(function(){
var count = 0;
$(".operational_cost_type").each(function() {
$(this).change(function(){
event.preventDefault();
var var_operational_cost_type = $(this).val();
var var_each_operational_cost = $(this).closest('.each_operational_cost');
var var_total_operational_cost = $(this).find('.total_operational_cost').val();
console.log(var_each_operational_cost);
});
count++;
});
});
Thank you so much!
You can get value of jumlah and biaya column using $(this).closest("tr").find.. then simply use .val() to add result inside your total column inputs.
Demo Code :
$(document).ready(function() {
var count = 0;
//if you need on chnage of input as well(else remove that input[type=number]..)
$(document).on("change input", ".operational_cost_type , input[type=number]", function() {
event.preventDefault();
var var_operational_cost_type = $(this).val();
var selector = $(this).closest("tr")
//get product quantity
var product_quantity = selector.find('.product_quantity').val();
var total_operational_cost = selector.find('.total_operational_cost')
//get opertional cost
var each_operational_cost = selector.find('.each_operational_cost').val();
//mutliply and add total to total col
total_operational_cost.val(product_quantity * each_operational_cost)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered table-responsive-md table-striped text-center">
<thead>
<tr>
<th class="text-center">Nama Cabang</th>
<th class="text-center">Jumlah</th>
<th class="text-center">Biaya Operasional</th>
<th class="text-center">Tipe Biaya</th>
<th class="text-center">Total</th>
</tr>
</thead>
<tbody class="distributionList">
<tr>
<td class="pt-3-half text-left">
something
</td>
<td class="pt-3-half">
<input type="number" class="form-control product_quantity" name="product_quantity[{{$fb->id}}]" id="product_quantity" value="0" placeholder="0">
</td>
<td class="pt-3-half">
<input type="number" class="form-control each_operational_cost" name="each_operational_cost[{{$fb->id}}]" id="each_operational_cost" value="0" placeholder="0">
</td>
<td class="pt-3-half">
<select class="form-control operational_cost_type" name="operational_cost_type" id="operational_cost_type">
<option value="pecentage">Pecentage</option>
<option value="flat">Number</option>
</select>
</td>
<td class="pt-3-half">
<input type="text" class="form-control total_operational_cost" name="total_operational_cost[{{$fb->id}}]" id="total_operational_cost" value="0" placeholder="0" readonly>
</td>
</tr>
<tr>
<td class="pt-3-half text-left">
something1
</td>
<td class="pt-3-half">
<input type="number" class="form-control product_quantity" name="product_quantity[{{$fb->id}}]" id="product_quantity" value="0" placeholder="0">
</td>
<td class="pt-3-half">
<input type="number" class="form-control each_operational_cost" name="each_operational_cost[{{$fb->id}}]" id="each_operational_cost" value="0" placeholder="0">
</td>
<td class="pt-3-half">
<select class="form-control operational_cost_type" name="operational_cost_type" id="operational_cost_type">
<option value="pecentage">Pecentage</option>
<option value="flat">Number</option>
</select>
</td>
<td class="pt-3-half">
<input type="text" class="form-control total_operational_cost" name="total_operational_cost[{{$fb->id}}]" id="total_operational_cost" value="0" placeholder="0" readonly>
</td>
</tr>
<tr>
<td class="pt-3-half text-left">
something2
</td>
<td class="pt-3-half">
<input type="number" class="form-control product_quantity" name="product_quantity[{{$fb->id}}]" id="product_quantity" value="0" placeholder="0">
</td>
<td class="pt-3-half">
<input type="number" class="form-control each_operational_cost" name="each_operational_cost[{{$fb->id}}]" id="each_operational_cost" value="0" placeholder="0">
</td>
<td class="pt-3-half">
<select class="form-control operational_cost_type" name="operational_cost_type" id="operational_cost_type">
<option value="pecentage">Pecentage</option>
<option value="flat">Number</option>
</select>
</td>
<td class="pt-3-half">
<input type="text" class="form-control total_operational_cost" name="total_operational_cost[{{$fb->id}}]" id="total_operational_cost" value="0" placeholder="0" readonly>
</td>
</tr>
</tbody>
</table>

How to display out put when doing calculations in Javascript?

I'm trying to calculate two numbers and display them but when I click Calculate Total nothing happens and no numbers are displayed. I've been looking for a solution for hours now and just can't figure out why nothing happens when I click the button. If someone could help me out a little bit I'd be very grateful!
function calcTotal() {
var intValue1 = parseInt(document.GetElementById('Value1').value);
var intValue2 = parseInt(document.GetElementById('Value2').value);
var strOper = document.GetElementById('operators').value;
if (strOper === '+') {
document.GetElementById('Total').value = intValue1 + intValue2;
else if (strOper === '-') {
document.GetElementById('Total').value = intValue1 - intValue2;
} else if (strOper === '*') {
document.GetElementById('Total').value = intValue1 * intValue2;
} else {
document.GetElementById('Total').value = intValue1 / intValue2;
}
}
document.getElementById('submit').onclick = calcTotal();
<table class="table1">
<tr>
<td class="label">
<label id="lblValue1" for="txtValue1">Value 1:</label>
</td>
<td class="control">
<input class="formFields" type="text" id="Value1" name="txtValue1" required>
</td>
</tr>
<tr>
<td>
<select name="dropdown" id="operators">
<option value="+" selected>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
</td>
</tr>
<tr>
<td class="label">
<label id="lblValue2" for="txtValue2">Value 2:</label>
</td>
<td class="control">
<input class="formFields" type="text" id="Value2" name="txtValue2" required>
</td>
</tr>
</table>
<hr>
<table>
<tr>
<td class="label">
<label id="lblTotal" for="txtTotal">Total:</label>
</td>
<td class="control">
<input class="textview" type="text" id="Total" name="txtTotal">
</td>
</tr>
</table>
<table>
<tr>
<td class="label">
<input id="submit" class="button" name='cmdCalcTotal' type="button" value="Calculate Total" onclick="calcTotal();">
</td>
</tr>
</table>
Thanks in advance!!!!
Your logic behind this code is actually working just fine. You just had a few syntax errors.
There was no closing brackets (}) for the if statement.
Also, you had .GetElementById(). You should've had .getElementById() (the g is supposed to be lowercase).
Also, you don't need to have a .onclick event in the javascript, if you already have on in the html. I removed that for you.
It's fixed in the snippet for you.
function calcTotal() {
var intValue1 = parseInt(document.getElementById('Value1').value);
var intValue2 = parseInt(document.getElementById('Value2').value);
var strOper = document.getElementById('operators').value;
if (strOper === '+') {
document.getElementById('Total').value = intValue1 + intValue2;
} else if (strOper === '-') {
document.getElementById('Total').value = intValue1 - intValue2;
} else if (strOper === '*') {
document.getElementById('Total').value = intValue1 * intValue2;
} else {
document.getElementById('Total').value = intValue1 / intValue2;
}
}
<table class="table1">
<tr>
<td class="label">
<label id="lblValue1" for="txtValue1">Value 1:</label>
</td>
<td class="control">
<input class="formFields" type="text" id="Value1" name="txtValue1" required>
</td>
</tr>
<tr>
<td>
<select name="dropdown" id="operators">
<option value="+" selected>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
</td>
</tr>
<tr>
<td class="label">
<label id="lblValue2" for="txtValue2">Value 2:</label>
</td>
<td class="control">
<input class="formFields" type="text" id="Value2" name="txtValue2" required>
</td>
</tr>
</table>
<hr>
<table>
<tr>
<td class="label">
<label id="lblTotal" for="txtTotal">Total:</label>
</td>
<td class="control">
<input class="textview" type="text" id="Total" name="txtTotal">
</td>
</tr>
</table>
<table>
<tr>
<td class="label">
<input id="submit" class="button" name='cmdCalcTotal' type="button" value="Calculate Total" onclick="calcTotal();">
</td>
</tr>
</table>
There are some error in your code:
Missing {} for if block
Uppercase GetElementById method, note that all function with uppercase are difference, also with css and Id and class.
Redundant //document.getElementById('submit').onclick = calcTotal();
If you want keep last line you can edit to
document.getElementById('submit').addEventListener("click", calcTotal);
and remove onclick="calcTotal();" on button
function calcTotal() {
var intValue1 = parseInt(document.getElementById('Value1').value);
var intValue2 = parseInt(document.getElementById('Value2').value);
var strOper = document.getElementById('operators').value;
if (strOper === '+') {
document.getElementById('Total').value = intValue1 + intValue2;
}
else if (strOper === '-') {
document.getElementById('Total').value = intValue1 - intValue2;
} else if (strOper === '*') {
document.getElementById('Total').value = intValue1 * intValue2;
} else {
document.getElementById('Total').value = intValue1 / intValue2;
}
}
document.getElementById('submit').addEventListener("click", calcTotal);
<table class="table1">
<tr>
<td class="label">
<label id="lblValue1" for="txtValue1">Value 1:</label>
</td>
<td class="control">
<input class="formFields" type="text" id="Value1" name="txtValue1" required>
</td>
</tr>
<tr>
<td>
<select name="dropdown" id="operators">
<option value="+" selected>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
</td>
</tr>
<tr>
<td class="label">
<label id="lblValue2" for="txtValue2">Value 2:</label>
</td>
<td class="control">
<input class="formFields" type="text" id="Value2" name="txtValue2" required>
</td>
</tr>
</table>
<hr>
<table>
<tr>
<td class="label">
<label id="lblTotal" for="txtTotal">Total:</label>
</td>
<td class="control">
<input class="textview" type="text" id="Total" name="txtTotal">
</td>
</tr>
</table>
<table>
<tr>
<td class="label">
<input id="submit" class="button" name='cmdCalcTotal' type="button" value="Calculate Total" >
</td>
</tr>
</table>

Create a dynamic array of JSON Object from values of multiple elements

I need a little help creating a dynamic array of JSON object from the values of different elements. Example is elements below. I have other elements to create the values required for JSON. I didnt want to post 3 lots of same code. So belwo x3
<tr>
<td style="width: 5%"><label>Title:</label></td>
<td><input type="text" class="leds" name="title" style="width:150px"value=""></td><tr>
<td style="width: 5%"><label>Message:</label></td>
<td><input type="text" class="leds" name="message" style="width: 150px" value=""></td><tr>
<td style="width: 5%"><label>IP address:</label></td>
<td><input type="text" class="leds" name="ip_address" style="width:150px" value=""></td>
<td style="width: 5%"><label>Message Colour:</label></td>
<td><select type="text" class="leds" name="led_colour" style="width:150px">
<option value=""></option>
<option value="255,0,0,0">Red</option>
<option value="0,255,0,0">Green</option>
<option value="0,0,255,0">Blue</option>
<option value="255,165,0,0">Orange</option>
<option value="255,255,0,0">Yellow</option>
<option value="255,255,255,0">White</option>
<option value="128,0,128,0">Purple</option>
<option value="255,0,255,0">Fuchsia</option>
<option value="192,192,192,0">Silver</option>
</td>
</tr>
I can get the values with the following
$.each($('.leds'), function(index, obj) {
console.log(index + ':' + obj.value);
});
What I would like to do is create JSON like below:
[{
"title": "Test1",
"message": "Test1 message",
"ip_address": "1.1.1.1",
"led_colour" : "255,0,0,0"},
{
"title": "Test2",
"message": "Test2 message",
"ip_address": "2.2.2.2",
"led_colour" : "255,0,0,0"},
{
"title": "Test3",
"message": "Test3 message",
"ip_address": "3.3.3.3",
"led_colour" : "255,0,0,0"
}]
A simple way is to loop each tr and get all .leds inputs, get the name of input and it's value an build object, then put it to array. See the code bellow.
var itemsArray = [];
$.each($('tr'), function() {
var item = {};
$(this).find('.leds').each(function(index, obj) {
item[$(obj).attr("name")]=$(obj).val();
});
itemsArray.push(item);
});
I think it's solution, but better need modify your html structure
1) In your case:
function getJson(keys) {
let result = [];
$('.leds').each(function(i) {
let keyIndex = i % keys.length,
key = keys[keyIndex];
if (!keyIndex) {
result.push({});
}
let index = result.length - 1;
result[index][key] = this.value;
})
return result;
}
const jsonData = getJson(['title', 'message', 'ip_address', 'led_colour']);
console.log('jsonData:', jsonData);
2) Try use tbody for group your tr
DEMO in Codepen.io
function getJson() {
let result = [];
$('tbody').each(function() {
let item = {}
$('.leds', this).each(function() {
let $this = $(this);
item[$this.prop('name')] = $this.val();
})
result.push(item);
})
console.log('result:', result)
return result;
}
$(() => {
getJson();
$('button').click(() => {
console.clear();
const jsonData = getJson();
alert(JSON.stringify(jsonData));
})
})
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button>Get Json Data</button>
<table>
<tbody>
<tr>
<td style="width: 5%">
<label>Title:</label>
</td>
<td>
<input type="text" name="title" style="width:150px" value="title1" class="leds"/>
</td>
</tr>
<tr>
<td style="width: 5%">
<label>Message:</label>
</td>
<td>
<input type="text" name="message" style="width: 150px" value="mess1" class="leds"/>
</td>
</tr>
<tr>
<td style="width: 5%">
<label>IP address:</label>
</td>
<td>
<input type="text" name="ip_address" style="width:150px" value="192.168.1.1" class="leds"/>
</td>
<td style="width: 5%">
<label>Message Colour:</label>
</td>
<td>
<select type="text" name="led_colour" style="width:150px" class="leds">
<option value=""></option>
<option value="255,0,0,0" selected="selected">Red</option>
<option value="0,255,0,0">Green</option>
<option value="0,0,255,0">Blue</option>
<option value="255,165,0,0">Orange</option>
<option value="255,255,0,0">Yellow</option>
<option value="255,255,255,0">White</option>
<option value="128,0,128,0">Purple</option>
<option value="255,0,255,0">Fuchsia</option>
<option value="192,192,192,0">Silver</option>
</select>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td style="width: 5%">
<label>Title:</label>
</td>
<td>
<input type="text" name="title" style="width:150px" value="title2" class="leds"/>
</td>
</tr>
<tr>
<td style="width: 5%">
<label>Message:</label>
</td>
<td>
<input type="text" name="message" style="width: 150px" value="mess2" class="leds"/>
</td>
</tr>
<tr>
<td style="width: 5%">
<label>IP address:</label>
</td>
<td>
<input type="text" name="ip_address" style="width:150px" value="192.168.1.2" class="leds"/>
</td>
<td style="width: 5%">
<label>Message Colour:</label>
</td>
<td>
<select type="text" name="led_colour" style="width:150px" class="leds">
<option value=""></option>
<option value="255,0,0,0" selected="selected">Red</option>
<option value="0,255,0,0">Green</option>
<option value="0,0,255,0">Blue</option>
<option value="255,165,0,0">Orange</option>
<option value="255,255,0,0">Yellow</option>
<option value="255,255,255,0">White</option>
<option value="128,0,128,0">Purple</option>
<option value="255,0,255,0">Fuchsia</option>
<option value="192,192,192,0">Silver</option>
</select>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td style="width: 5%">
<label>Title:</label>
</td>
<td>
<input type="text" name="title" style="width:150px" value="title3" class="leds"/>
</td>
</tr>
<tr>
<td style="width: 5%">
<label>Message:</label>
</td>
<td>
<input type="text" name="message" style="width: 150px" value="mess3" class="leds"/>
</td>
</tr>
<tr>
<td style="width: 5%">
<label>IP address:</label>
</td>
<td>
<input type="text" name="ip_address" style="width:150px" value="192.168.1.3" class="leds"/>
</td>
<td style="width: 5%">
<label>Message Colour:</label>
</td>
<td>
<select type="text" name="led_colour" style="width:150px" class="leds">
<option value=""></option>
<option value="255,0,0,0" selected="selected">Red</option>
<option value="0,255,0,0">Green</option>
<option value="0,0,255,0">Blue</option>
<option value="255,165,0,0">Orange</option>
<option value="255,255,0,0">Yellow</option>
<option value="255,255,255,0">White</option>
<option value="128,0,128,0">Purple</option>
<option value="255,0,255,0">Fuchsia</option>
<option value="192,192,192,0">Silver</option>
</select>
</td>
</tr>
</tbody>
</table>

jquery select option by text not working properly

In my code there are three select elements (one for each file) with 3 or 4 options each. I have added one Apply All button on the row having first file.
If an user selects the sheet name on the first file and clicks on Apply All button, it has to select same sheets on all the files. If the sheet was missing on anyone of the files, it has to show an alert like "mismatched sheets". Here is what I tried,
<form method="post" id="sheetForm" action="#"><input type="hidden" name="csrfmiddlewaretoken" value="cR9fmhJk0hhQF0FIFscTABn3DXnXMPNPAOu2cZhSwFwRfC0FleEUJnlVsqbC2I4D">
<div class="row">
<div class="col-sm-12">
<div class="m-b-15">
</div>
</div>
</div>
<div class="row">
<div class="m-b-30 form-group">
<label class="col-md-4 control-label">Sheet Select Mode</label>
<div class="col-md-8">
<label class="radio-inline">
<input type="radio" id="inlineRadio1" value="option1" name="radioInline">By Name
</label>
<label class="radio-inline">
<input type="radio" id="inlineRadio2" value="option2" name="radioInline">By Position
</label>
</div>
</div>
<table id="tblPreview" class="table table-hover dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>File Name</th>
<th>Sheet Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="file-name">test-data-input-xls-mult-feb.xlsx</td>
<input type="hidden" name="filename" value="test-data-input-xls-mult-feb.xlsx">
<td>
<select id="select1" class="form-control input-small sheet-select" name="sheet-select">
<option value="name 1" selected="selected" >Sheet1</option>
<option value="index 1">1</option>
<option value="name 2">Sheet2</option>
<option value="index 2">2</option>
</select>
</td>
<td class="open">
<button type="button" id="btnApplyAll" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="true">Apply All Files </button>
</td>
</tr>
<tr>
<td class="file-name">test-data-input-xls-mult-jan.xlsx</td>
<input type="hidden" name="filename" value="test-data-input-xls-mult-jan.xlsx">
<td>
<select id="select2" class="form-control input-small sheet-select" name="sheet-select">
<option value="name 1" selected="selected">Sheet1</option>
<option value="index 1">1</option>
<option value="name 2" >Sheet2</option>
<option value="index 2" >2</option>
</select>
</td>
<td>
</td>
</tr>
<tr>
<td class="file-name">test-data-input-xls-mult-mar.xlsx</td>
<input type="hidden" name="filename" value="test-data-input-xls-mult-mar.xlsx">
<td>
<select id="select3" class="form-control input-small sheet-select" name="sheet-select">
<option value="name 1" selected="selected" >Sheet1</option>
<option value="index 1" >1</option>
<option value="name 2" >Sheet2</option>
<option value="index 2">2</option>
</select>
</td>
<td>
</td>
</tr>
</tbody>
</table>
</div>
</form>
and the relevant js code looks like,
$('#btnApplyAll').on('click', function(){
// get the selected option of first select
var noSuchOption = false;
var selectedOption = $('#select1').find(":selected").text();
var selects = $('select[name="sheet-select"]');
$('select[name="sheet-select"] option[selected="selected"]').removeAttr('selected');
$.each(selects, function(index, select) {
var opts = $(select).find('option').filter(function(){ return this.text == selectedOption;});
if(opts.length < 1) {
noSuchOption = true;
return false;
}
});
if(noSuchOption) {
notify_long("Selected sheet doesn't exists in all files!", 'danger');
} else {
$('select[name="sheet-select"] option').filter(function(){
return this.text == selectedOption;
}).attr('selected', true);
}
});
This piece of code works on the initial stage of 3 or 4 button clicks but if I click on apply all button after choosing sheet1 on file1, sheet2 on file2, sheet1 on file3 at the middle stage, it fails to change. On that time, switching between radio buttons also fails to display the relevant option.
jsFiddle
This could meet your requirements:
$('#btnApplyAll').on('click', function(){
var noSuchOption = false;
var selectedOption = null;
$('select.sheet-select').each(function(index) {
if (noSuchOption) return;
if (index == 0) {
selectedOption = $(this).val();
return;
}
if ($(this).find('option[value="' + selectedOption + '"]').length === 0) {
noSuchOption = true;
alert("File: "+$(this).parent().prev().val() +" have not selected sheet", 'danger');
return;
}
$(this).val(selectedOption);
})
});
function toggleOptions(e) {
var toggle = $(this).attr('id') == 'inlineRadio1' ? 'name' : 'index';
$('select.sheet-select option').hide()
$('select.sheet-select').each(function() {
let optsToShow = $(this).find('option[value^="'+ toggle +'"]');
optsToShow.show();
$(this).val(optsToShow.first().attr('value'));
});
}
$('#inlineRadio1, #inlineRadio2')
.change(toggleOptions)
.first().change(); // trigger change to initialize
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="sheetForm" action="#">
<input type="hidden" name="csrfmiddlewaretoken" value="cR9fmhJk0hhQF0FIFscTABn3DXnXMPNPAOu2cZhSwFwRfC0FleEUJnlVsqbC2I4D">
<div class="row">
<div class="m-b-30 form-group">
<label class="col-md-4 control-label">Sheet Select Mode</label>
<div class="col-md-8">
<label class="radio-inline">
<input type="radio" id="inlineRadio1" value="option1" name="radioInline" checked>By Name
</label>
<label class="radio-inline">
<input type="radio" id="inlineRadio2" value="option2" name="radioInline">By Position
</label>
</div>
</div>
<table id="tblPreview" class="table table-hover dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>File Name</th>
<th>Sheet Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="file-name">test-data-input-xls-mult-feb.xlsx</td>
<input type="hidden" name="filename" value="test-data-input-xls-mult-feb.xlsx">
<td>
<select id="select1" class="form-control input-small sheet-select" name="sheet-select-feb">
<option value="name 1" selected="selected" >Sheet1</option>
<option value="index 1">1</option>
<option value="name 2">Sheet2</option>
<option value="index 2">2</option>
<option value="name 3">Sheet3</option>
</select>
</td>
<td class="open">
<button type="button" id="btnApplyAll" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="true">Apply All Files </button>
</td>
</tr>
<tr>
<td class="file-name">test-data-input-xls-mult-jan.xlsx</td>
<input type="hidden" name="filename" value="test-data-input-xls-mult-jan.xlsx">
<td>
<select id="select2" class="form-control input-small sheet-select" name="sheet-select-jan">
<option value="name 1" selected="selected">Sheet1</option>
<option value="index 1">1</option>
<option value="name 2" >Sheet2</option>
<option value="index 2" >2</option>
</select>
</td>
<td>
</td>
</tr>
<tr>
<td class="file-name">test-data-input-xls-mult-mar.xlsx</td>
<input type="hidden" name="filename" value="test-data-input-xls-mult-mar.xlsx">
<td>
<select id="select3" class="form-control input-small sheet-select" name="sheet-select-mar">
<option value="name 1" selected="selected" >Sheet1</option>
<option value="index 1">1</option>
<option value="name 2" >Sheet2</option>
<option value="index 2">2</option>
</select>
</td>
<td>
</td>
</tr>
</tbody>
</table>
</div>
</form>
$(document).ready(function() {
// Default select mode of sheet
$(".rdoSelection[value='byName']").prop("checked", true);
function selectCheckboxstatus() {
var selectionMode;
$(".clsDdPosition").prop("selectedIndex", 0);
$(".clsDdName").prop("selectedIndex", 0);
selectionMode = $(".rdoSelection:checked").val();
if ("byName" === selectionMode) {
$(".clsDdPosition").hide();
$(".clsDdName").show();
} else if ("byPosition" === selectionMode) {
$(".clsDdPosition").show();
$(".clsDdName").hide();
}
}
selectCheckboxstatus();
$(".rdoSelection").on("click", function(e) {
selectCheckboxstatus();
});
$(".btnApplyAll").on("click", function(e) {
var selectedValue, selectedClass, ddSelectionMode;
ddSelectionMode = $(".rdoSelection:checked").val(); if ("byName" === ddSelectionMode) {
selectedValue = $("#ddSheetByName1").val();
selectedClass = ".clsDdName";
} else if ("byPosition" === ddSelectionMode) {
selectedValue = $("#ddSheetByPosition1").val();
selectedClass = ".clsDdPosition";
}
$(selectedClass).each(function() {
$(this).val(selectedValue);
});
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="sheetForm" action="#">
<input type="hidden" name="csrfmiddlewaretoken" value="cR9fmhJk0hhQF0FIFscTABn3DXnXMPNPAOu2cZhSwFwRfC0FleEUJnlVsqbC2I4D">
<div class="row">
<div class="col-sm-12">
<div class="m-b-15">
</div>
</div>
</div>
<div class="row">
<div class="m-b-30 form-group">
<label class="col-md-4 control-label">Sheet Select Mode</label>
<div class="col-md-8">
<label class="radio-inline">
<input type="radio" id="inlineRadio1" value="byName" name="radioInline" class="rdoSelection">By Name
</label>
<label class="radio-inline">
<input type="radio" id="inlineRadio2" value="byPosition" name="radioInline" class="rdoSelection">By Position
</label>
</div>
</div>
<table id="tblPreview" class="table table-hover dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>File Name</th>
<th>Sheet Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="file-name">test-data-input-xls-mult-feb.xlsx</td>
<input type="hidden" name="filename" value="test-data-input-xls-mult-feb.xlsx">
<td>
<select id="ddSheetByName1" class="form-control input-small ddSheetByName1 clsDdName" name="sheet-select">
<option value="sheet1">Sheet1</option>
<option value="sheet2">Sheet2</option>
</select>
<select id="ddSheetByPosition1" class="form-control input-small ddSheetByPosition1 clsDdPosition" name="sheet-select">
<option value="index1">1</option>
<option value="index2">2</option>
</select>
</td>
<td class="open">
<button type="button" id="btnApplyAll" class="btn btn-default dropdown-toggle btnApplyAll" data-toggle="dropdown" aria-expanded="true">Apply All Files </button>
</td>
</tr>
<tr>
<td class="file-name">test-data-input-xls-mult-jan.xlsx</td>
<input type="hidden" name="filename" value="test-data-input-xls-mult-jan.xlsx">
<td>
<select id="ddSheetByName2" class="form-control input-small ddSheetByName2 clsDdName" name="sheet-select">
<option value="sheet1">Sheet1</option>
<option value="sheet2">Sheet2</option>
</select>
<select id="ddSheetByPosition2" class="form-control input-small ddSheetByPosition2 clsDdPosition" name="sheet-select">
<option value="index1">1</option>
<option value="index2">2</option>
</select>
</td>
</tr>
<tr>
<td class="file-name">test-data-input-xls-mult-mar.xlsx</td>
<input type="hidden" name="filename" value="test-data-input-xls-mult-mar.xlsx">
<td>
<select id="ddSheetByName3" class="form-control input-small ddSheetByName3 clsDdName" name="sheet-select">
<option value="sheet1">Sheet1</option>
<option value="sheet2">Sheet2</option>
</select>
<select id="ddSheetByPosition3" class="form-control input-small ddSheetByPosition3 clsDdPosition" name="sheet-select">
<option value="index1">1</option>
<option value="index2">2</option>
</select>
</td>
</tr>
</tbody>
</table>
</div>
</form>

How to get specific HTML control from a <table><tr><td></td></tr></table> and append the selected control to the same <td>?

I've following table in HTML:
<table id="blacklistgrid_1" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th style="vertical-align:middle">Products</th>
<th style="vertical-align:middle">Pack Of</th>
<th style="vertical-align:middle">Quantity</th>
<th style="vertical-align:middle">Volume</th>
<th style="vertical-align:middle">Unit</th>
<th style="vertical-align:middle">Rebate Amount</th>
</tr>
</thead>
<tbody class="apnd-test">
<tr id="reb1_1">
<td>
<div class="btn-group">
<select name="product_id_1[1]" id="product_id_1_1" class="form-control prod_list">
<option value="" selected='selected'>Select Product</option>
</select>
</div>
</td>
<td><input type="text" name="pack[1]" id="pack_1" value="" class="form-control" size="8"/></td>
<td><input type="text" name="quantity[1]" id="quantity_1" value="" class="form-control" size="8"/></td>
<td><input type="text" name="volume[1]" id="volume_1" value="" class="form-control" size="8"/></td>
<td>
<div class="btn-group">
<select name="units[1]" id="units_1" class="form-control">
<option value="" selected='selected'>Select Unit</option>
<option value="5" >Microsecond</option>
<option value="7" >oz</option>
<option value="9" >ml</option>
<option value="10" >L</option>
<option value="12" >gms</option>
</select>
</div>
</td>
<td><input type="text" name="amount[1]" id="amount_1" value="" class="form-control" size="9"/></td>
</tr>
</tbody>
<tfoot>
<tr id="reb1_2">
<td><button style="float:right; margin-bottom: 20px" class="products" type="button" class="btn btn-default" onclick=""> Add</button></td>
<td colspan="5"></td>
</tr>
</tfoot>
</table>
Now I've to append the
<select name="product_id_1[1]" id="product_id_1_1" class="form-control prod_list">
<option value="" selected='selected'>Select Product</option>
</select>
to the <td> in which it is present currently on the click of Add button. Previously the functionality was of adding the entire row with <select></select> in first <td> of a new <tr> but now the requirement is to append the <select></select> to the existing <td> only. My previous code is as follows:
$(document).delegate('.products','click',function (e) {
var table_id = $(this).closest('table').attr('id');
var no = table_id.match(/\d+/)[0];
var first_row = $('#'+table_id).find('tbody tr:first').attr('id');
var new_row = $('#'+first_row).clone();
var tbody = $('#' + table_id + ' tbody');
var n = $('tr', tbody).length + 1;
new_row.attr('id', 'reb' + no +'_'+ n);
$(':input', new_row).not('.prod_list').remove();
$('select', new_row).attr('name','product_id_'+no+'['+n+']');
$('select', new_row).attr('id','product_id_'+no+'_'+n);
$('<button style="color:#C00; opacity: 2;margin-top: 6px;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">×</button>').appendTo( $(new_row.find('td:first')) );
tbody.append(new_row);
$(new_row).children('td').not('td:eq(0)').remove();
});
But please note that the id and name of the <select></select> to be appended should be in same fashion as of my previous functionality. You can refer above code for it. Thanks in advance.
you can try this below javascript code,
var count = 1;
$('#blacklistgrid_1').on('click', '.products', function () {
var n = $('.pro:last').attr('name').match(/\[(.*?)\]/);
var newName = $('.pro:last').attr('name').replace(/\[(.*?)\]/, '[' + (+n[1] + 1) + ']');
var newID = $('.pro:last').attr('id').replace(/[^_]*$/, +n[1] + 1);
var toCloneDiv = $('.selectControls:last').clone();
var clonedDiv = $(toCloneDiv).appendTo('#reb1_1 > td:nth-child(1)');
//add delete button
if (count == 1) $('<button style="color:#C00; opacity: 2;margin-top: 6px;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">×</button>').appendTo(clonedDiv);
count++;
$(clonedDiv).find('.pro').attr({
'id': newID,
'name': newName
});
});
// to remove select element
$('#blacklistgrid_1').on('click','.close', function(){
$(this).closest('div').remove();
});
SEE THIS FIDDLE DEMO

Categories

Resources