I am working on a script to add a row to a form using js.
this is the js script I have.
<script>
jQuery(function($) {
var $button = $('#add-row'),
$row = $('.timesheet-row').clone();
$button.click(function() {
$row.clone().insertAfter('#clone-row');
});
});
</script>
Then my form's elements are set up like this.
<div class="form-group col-lg-2">
<label>In Time</label>
<input class="form-control" type="datetime" id="intime" name="intime[]">
</div>
My problem is I cant seem to figure out how to retrieve the values of the form fields
here is the jfiddle
jfiddle
Updated jfiddle to revised code to post to php file
<?php
$pos= $_POST['position'];
$position = json_decode($pos);
echo $position;
echo "This should work";
If anymore than one line is found no response is returned.
Basically you'll need to iterate through the elements to get their values.
.each() will help you in that.
select an element input or select with their name and call .each() on it.
In .each() fetch the value of current element and store it.
Here's the updated jsFiddle.
I took the liberty of adding a button(id = "get-row-values") on whose click you'll see an alert with all the values of your inputs and selects in .timesheet-row.
Also I removed [] from the names of your inputs and selects.
$("#get-row-values").click(function () {
var position = "";
var unit = "";
var employee = "";
var intime = "";
var outtime = "";
$(".timesheet-row select[name=position]").each(function () {
position += " " + $(this).val();
});
$(".timesheet-row select[name=unit]").each(function () {
unit += " " + $(this).val();
});
$(".timesheet-row select[name=employee]").each(function () {
employee += " " + $(this).val();
});
$(".timesheet-row input[name=intime]").each(function () {
intime += " " + $(this).val();
});
$(".timesheet-row input[name=outtime]").each(function () {
outtime += " " + $(this).val();
});
alert("Positions : " + position + "\nUnits : " + unit + "\nEmployees : " + employee + "\nIntimes : " + intime + "\nOuttimes : " + outtime);
});
Related
Having a tuff time figuring this out. I am building a front-end WooCommerce cart component that will add multiple products to the cart by passing the product ID into the URL. The URL structure will ultimately look like this http://cleancolor.staging.wpengine.com/?add-to-cart=2998,3339,2934 where the 2998,3339,2934 are the WooCommerce Product ID's.
Here is a live working version (without the append) http://studiorooster.com/dojo/cleancolor/ - just click on a "5 Pack" or "10 Pack" and select an addon. I have the product id's appended to the Addon name to the right side list and have the attribute named data-itemid
Here is my html block
<div class="col-md-3 clearfix" id="order_summary_box">
<div class="summary-box">
<div class="heading-total">Order Summary : <span class="color-txt" id="order_total"><span>$</span>0</span>
</div>
<div class="summary-basic-pack">
<h5>Whats in Your Bundle</h5>
<ul class="entree-add" id="entree-add">
<li id="no-entrees">No Entrees Added</li>
</ul>
<ul class="pack-add" id="pack-add">
<li id="no-addons">No Addons Selected</li>
</ul>
</div>
<div class="orderbtn-area">
<div class="order-btn-cont"><i class="fa fa-check-circle-o" aria-hidden="true"></i> Subscribe Now !</div>
</div>
</div>
</div>
jQuery
$('#get-started').delegate('.check-opt', 'click', function () {
let cost = '0';
let itemname = '';
let first = '';
let itemid = ''
if ($(this).is(':checked')) {
cost = $(this).attr('data');
itemid = $(this).attr('data-itemid');
order_additional_options += Number(cost);
itemname = $(this).attr('value');
first = itemname.slice(0, itemname.indexOf(" "));
$("#no-addons").remove();
$(".pack-add").append("<li data-cost='" + cost + "' data-id='item_" + first + cost + "' data-itemid='" + itemid + "'>" + itemname + itemid + "</li>");
} else { // minus unchecked value
cost = $(this).attr('data');
itemname = $(this).attr('value');
first = itemname.slice(0, itemname.indexOf(" "));
order_additional_options -= Number(cost);
$('[data-id=item_' + first + cost + ']').remove();
}
cart_update();
});
// on click order button submit the form
$('#order_btn_id').on("click", function () {
$('a').attr("href", "http://cleancolor.staging.wpengine.com/?add-to-cart=");
});
Determine whether the window has a push stat
Find all elements that are added to the .pack-add and extract their number
Compile a , delimited string
The following sections that starts and end with //*************
in the snip below should do the trick. Probably you can refactor it into a function.
// add and remove check box items on summary
$('#get-started').delegate('.check-opt', 'click', function () {
let cost = '0';
let itemname = '';
let first = '';
let itemid = ''
if ($(this).is(':checked')) {
cost = $(this).attr('data');
itemid = $(this).attr('data-itemid');
order_additional_options += Number(cost);
itemname = $(this).attr('value');
first = itemname.slice(0, itemname.indexOf(" "));
$("#no-addons").remove();
$(".pack-add").append("<li data-cost='" + cost + "' data-id='item_" + first + cost + "' data-itemid='" + itemid + "'>" + itemname + itemid + "</li>");
// ********************* INSERTED CODES
var all_values=""
$(".pack-add").children().each(function(){
all_values+=$(this).attr('data-itemid')+" "
})
console.log(all_values.trim().replace(" ",","));
var query_string="?add-to-cart="+all_values.trim().replace(/ /g,",");
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + query_string;
window.history.pushState({path:newurl},'',newurl);
}
// **********************END OF NEW CODES
} else { // minus unchecked value
cost = $(this).attr('data');
itemname = $(this).attr('value');
first = itemname.slice(0, itemname.indexOf(" "));
order_additional_options -= Number(cost);
$('[data-id=item_' + first + cost + ']').remove();
// ********************* INSERTED CODES
var all_values=""
$(".pack-add").children().each(function(){
all_values+=$(this).attr('data-itemid')+" "
})
console.log(all_values.trim().replace(" ",","));
var query_string="?add-to-cart="+all_values.trim().replace(/ /g,",");
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + query_string;
window.history.pushState({path:newurl},'',newurl);
}
}
cart_update();
});
I assume this is a common problem, but I haven't been able to find the answer in other threads.
The basic idea / goal here is that if a task is marked as important, it gets added to quadrant1. If it isn't, it gets added to quadrant2. When tasks are completed, they can be closed out by clicking on them.
HTML:
I have a simple page with:
A text input (i.e. "task")
Checkbox (i.e. "important")
Submit button (i.e. "submitTask")
Two divs ("quadrant1" and "quadrant2").
JS:
$(document).ready( function () {
$('#submitTask').on("click", function() {
var task = $("#task").val();
var important = $("#important").prop("checked");
var addToQuadrant = function (task, important) {
if (important == true) {
$("#quadrant1").append(
"<p class='taskHolder'> " + task + " </p>");
} else if (important == false) {
$("#quadrant2").append(
"<p class='taskHolder'> " + task + " </p>");
}
});
});
addToQuadrant(task, important);
$('body').on('click', '.taskHolder', function () {
$('.taskHolder').slideUp();
});
});
My problem is that since I use the same id (i.e. "taskHolder") for both paragraph elements, if I add more than one task to my page at a time, I can't remove more than one of them.
My question is: how can I dynamically add an element to the DOM while also giving it a unique id or selector so every task can be uniquely targeted and closed out?
Use:
$(this).slideUp();
instead of
$('.taskHolder').slideUp();
Within the event handler this references the element that the event applied to.
The following is the minimal code I'd use to implement your whole thing:
$(document).ready(function() {
var task = $("#task");
var cb = $("#important");
$("button").click(function() {
$("<p></p>", {
text: task.val(),
"class": "task"
}).appendTo(cb[0].checked ? "#quadrant1" : "#quadrant2");
});
$("body").on("click", ".task", function() {
$(this).slideUp(500, function(){ $(this).remove(); });
});
});
div { border: thin black solid; margin: 4px; min-height: 20px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>Task: <input id="task"></label>
<label><input type="checkbox" id="important"> Important</label>
<button>Add</button>
<div id="quadrant1"></div>
<div id="quadrant2"></div>
User a global variable 'counter' and increase its value at each click then append this with 'taskHolder'. Now you have unique id for each task.
To select use startwith type selector.
var cnt = 0;
$(document).ready( function () {
$('#submitTask').on("click", function() {
cnt++;
var task = $("#task").val();
var important = $("#important").prop("checked");
var addToQuadrant = function (task, important) {
if (important == true) {
$("#quadrant1").append(
"<p id='taskHolder" + cnt + "' > " + task + " </p>");
} else if (important == false) {
$("#quadrant2").append(
"<p id='taskHolder" + cnt + "'> " + task + " </p>");
};
addToQuadrant(task, important);
$('[id^=taskHolder]').on("click", function() {
$(this).slideUp();
};
});
Alternative solution
A better solution could be common class to each of the tasks
"<p class='commonClass" + cnt + "'> " + task + " </p>");
and
$('body').on('click', '.taskHolder', function () {
$(this).slideUp();
});
You need to apply the new ID for the each newly added element dynamically.
//New length every time you click
var newLength = $('[id^=taskHolder]').length + 1;
//Apply the new ID
$("#quadrant1").append(
"<p id='taskHolder+newLength+'> New " + newLength + " </p>");
$('#submitButton').click(function(){
//New length every time you click
var newLength = $('[id^=taskHolder]').length + 1;
//Apply the new ID
$("#quadrant1").append(
"<p id='taskHolder+newLength+'> New " + newLength + " </p>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quadrant1">
<p id="taskHolder_1">New 1</p>
</div>
<button id="submitButton">Button</button>
Use unique id
Target item with $(this) to hide on complete.
$(document).ready( function () {
var addToQuadrant = function (task, important) {
if (important == true) {
var taskid = $("#quadrant1").length + 1;
$("#quadrant1").append(
"<p class='taskHolder' id='task-"+taskid+"'> " + task + " </p>");
} else if (important == false) {
var imptaskid = $("#quadrant2").length + 1;
$("#quadrant2").append(
"<p class='taskHolder' id='imp-task-"+imptaskid+"'> " + task + " </p>");
};
};
$('#submitTask').on("click", function() {
var task = $("#task").val();
var important = $("#important").prop("checked");
addToQuadrant(task, important);
});
$('body').on('click', '.taskHolder', function () {
$( this ).slideUp();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Important Task
<div id="quadrant1" style="border:1px dotted;min-height:20px;margin-bottom: 10px">
</div>
Task
<div id="quadrant2" style="border:1px dotted;min-height:20px;margin-bottom: 10px">
</div>
Task: <input type="text" id="task" />
<input type="checkbox" id="important" /> Important
<input type="button" value="Submit" id="submitTask" />
So I have this javascript function that loops through each user account and displays them in a drop-down menu. When the user selects an option from the drop-down menu, it takes the Iban number as its main id which is stored in ddlAccountFrom. Is there a way how I can store two values when the user selects an option, like for instance the Iban and Currency into separate variables?
function getAccountFrom() {
var username = $("#hiddenUsername").val();
var url = "http://localhost:63723/api/BankAccountsApi/GetBankAccounts/?username=" + username + "&id=2";
$.getJSON(url, function (data) {
var table = "<select id=\"ddlAccountFrom\">";
table += "<option value=\"-1\">Select an Account</option>";
$.each(data, function (key, val) {
table += "<option value=\"" + val.Iban + "\">" + val.Iban + " | " + val.Currency + " | " + val.Balance + "</option>";
});
table += "</select>";
$('#divAccountFrom').html(table);
});
}
I am using the ddlAccountFrom in this function..
function Transfer() {
var accountFrom = $("#ddlAccountFrom").val();
var accountTo = $("#txtAccountTo").val();
var amount = $("#txtAmount").val();
var url = "http://localhost:63723/api/BankAccountsApi/TransferFunds/?
ibanFrom=" + accountFrom + "&ibanTo=" + accountTo + "&amount=" + amount;
$.getJSON(url, function (data) {
alert(data);
})
.error (function () {
alert("Not enough balance! The amount entered exceed the balance found in this account. Please try again.");
})
}
You can use the data-custom attribute, like this:
table += "<option value=\"" + val.Iban + "\" data-currency=\"" + val.Currency + "\">" + val.Iban + " | " + val.Currency + " | " + val.Balance + "</option>";
To access variable see jquery-cant-get-data-attribute-value
So you can read:
var selectedCurrency= $("#ddlAccountFrom :selected").data('currency');
You could :
Concatenate your 2 data in 1 string with a separator (for ex myIban#myCurrency) and then split your value to get back your 2 distinct data
Listen to your dropdown changes, for example adding a onchange=updateData(val.Iban, val.Currency) attribute to your option html, and in your js :
var currentIban, currentCurrency;
function updateData(iban, currency) {
currentIban = iban;
currentCurrency = currency;
}
Add a data-custom attribute, like data-currency or data-iban
In below context menu example .. how to get value of fist column that invoked it?
Refer Link
tried with $(this).find('td:first').text() but it didnt work.
How to do this?
In your case you can do this:
menuSelected: function (invokedOn, selectedMenu) {
var value = invokedOn.parent().children(':first').text();
var msg = "You selected the menu item '" + selectedMenu.text() +
"' on the value '" + value + "'";
alert(msg);
}
Demo: http://jsfiddle.net/X9tgY/402/
here its working
var arr = [];
$("#myTable tr").each(function(){
arr.push($(this).find("td:first").text()); //put elements into array
});
alert(arr);
Consider this code:
invokedOn.closest('table').find('tr td:first').text()
Complete code:
menuSelected: function (invokedOn, selectedMenu) {
var msg = "You selected the menu item '" + selectedMenu.text() +
"' on the value '" + invokedOn.closest('table').find('tr td:first').text() + "'";
alert(msg);
}
DEMO
I have a function where I read the the text input value and update a counter which is displayed in another div. In some cases I show a check box along with text input field. At the moment when user select the check box the amount which is entered in the text input field is doubled and the result is showing in the counter correctly.
What am I trying to achieve id when the user select the check box the input field should be doubled along with the counter.
The text input in the betslip is added dynamically. So there might be more individual betlsips with check boxes in the view.
Here is my code (HTML view is generated dynamically through JS)
BetSlip.prototype.createSingleBetDiv = function(divId, Bet, winPlaceEnabled) {
document.betSlip.setSingleCount($('[name=singleBet]').length);
var id = divId.replace('_div','');
// If such bet already exists
if (!document.betSlip.singleDivExists(divId) && document.betSlip.getSingleCount() < maxNumberInBetslipRacing) {
var singleBetPosition = (Bet.position == null) ? '' : Bet.position;
var raceInfo = Bet.categoryName + ', ' + raceFullName + ' ' + Bet.name + ', ' + Bet.betTypeName + ' (' + Bet.value.toFixed(2) + ')';
var div = $('<div name="singleBet" class="bet gray2" id="' + divId + '"/>')
// Appending div with data
.data('Bet', Bet)
// Appending error element
$(div).append($('<p id="' + divId + '_error" style="display:none;"/>')
.addClass('alert alert-danger alert-dismissable'))
// Appending info element
$(div).append($('<p id="' + divId + '_info" style="display:none;"/>')
.addClass('alert alert-success alert-dismissable'))
var bgDiv = $('<div id="bgDiv"/>').appendTo(div)
// Append left part
var productName = (Bet.productName != null) ? getBrandBetName(Bet.productName) : Bet.betTypeName;
var leftDiv = $('<div class="left"/>')
.appendTo(div)
// Info abt the bet
.append($('<p class="title"><b>' + singleBetPosition + ' ' + Bet.horseName + '</b><span style="float:right">' + productName + '</span></p>'))
.append($('<p class="title">' + raceInfo + '</p>'))
.append($('<p/>')
.addClass('supermid')
// Creating input field
.append($('<input type="text" id="' + id + '_input"/>')
.keypress(function(event) {validateInputs(event, 'decimal')})
.keyup(function() {document.betSlip.updateSinglesTotalPrice()})))
// Creating WIN / PLACE checkbox selection
if (winPlaceEnabled) {
$(leftDiv).append($('<p><input name="winPlaceCheckBox" id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>')
.click(function() {document.betSlip.updateSinglesTotalPrice()}))
}
// Append Done and Reuse btns
$(leftDiv).append($('<a id="reuseBtn" class="button confirm gray reuse" style="display: none;"/>').html(reuse).click(function() {document.betSlip.reuseBet(divId)}))
$(leftDiv).append($('<a id="doneBtn" class="button confirm red donebtn" style="display: none"/>').html(done)
.click(function(){$('#' + divId).find('a.right.orange').click()}))
// Append right part
$(div).append($('<a class="right orange"/>')
.click(function() {
document.betSlip.removeSingleBetDiv(divId);
})
// Closing btn
.append($('<div class="icon_shut_bet"/>')))
// Add div to the bet slip map
document.betSlip.addSingleDiv(divId, div);
return div;
}
else {
if(this.getSingleCount() < maxNumberInBetslipRacing){
$("#betSlipError").show();
$("#betSlipError").html(sameBet);
return null;
}
else{
$("#betSlipError").show();
$("#betSlipError").html(maxBet);
return null;
}
}
}
In the win/place check box I am calling a function which take cares of updating the final price in the counter (Total bet). I would like to update the same in the input text field as well (double up the input value). In case check box is deselected the input amount should be half (both in input field as well as in the counter).
Function which updated the total bet value
BetSlip.prototype.updateSinglesTotalPrice = function() {
var totalBet = 0;
$('[name=singleBet]').each(function() {
var inputValue = $(this).find('input:text').val();
// Win / Place
if (document.betSlip.checkWinPlace(this)) totalBet += Number(inputValue * 2);
// Win or Place
else totalBet += Number(inputValue);
});
$("#betSinglesTotalBet").html(replaceParams(totBetPrice, [totalBet.toFixed(2), document.betSlip.getCurrency()]));
}