I'm having a bear of a time getting this input to focus. It is dynamically loaded. On the blur of the input, it is supposed to do some checking and then go back to that input if incorrect id entered. $(itemID) is what I am trying to focus.
Here is my javascript function that is called on page load.
function addBlurEvent() {
$("#brochureItems").on("blur", ".item-ID", (function (e) {
var itemID = $(this);
var itemIDVal = $.trim($(this).val());
if (itemIDVal != "") {
var item = "";
$.each(window.listOfItems, function(i, v) {
if (v.No.search(itemIDVal) != -1) {
item = v.Description;
return;
}
});
if(item != "") {
$(itemID).parent().parent().siblings(".item-desc").find("input").first().val(item);
$(itemID).parent().siblings(":last").find("input").first().focus();
} else {
slideDownMsg("Item: " + itemIDVal + " not found.");
slideUpMsg(3000);
$(itemID).focus();
}
} else {
$(itemID).parent().siblings(".item-desc").find("input").first().val("");
$(itemID).parent().siblings(":last").find("input").val("")
}
}));
$(".removeRow").on('click', function() {
$(this).closest("tr").remove();
});
}
And here is the dynamically added table:
<table class="table table-bordered table-striped" id="brochureItems">
<thead>
<tr>
<th>
Item Code
</th>
<th>
Brochure Code
</th>
<th width="35%">
Item Description
</th>
<th>
Retail
</th>
<th>
Remove
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="row">
<div class="col-md-8">
<input id="brochureItems_0__itemNo" class="form-control text-box single-line valid item-ID" data-val="true" data-val-required="The Item Code field is required." name="brochureItems[0].itemNo" aria-invalid="false" type="text">
</div>
</td>
<td class="row">
<div class="col-md-8">
<input id="brochureItems_0__brocCode" class="form-control text-box single-line" data-val="true" data-val-required="The Brochure Code field is required." name="brochureItems[0].brocCode" type="text">
</div>
</td>
<td class="row item-desc">
<div class="col-md-12">
<input id="brochureItems_0__itemDesc" class="form-control text-box single-line" data-val="true" data-val-required="The Item Description field is required." name="brochureItems[0].itemDesc" readonly="readonly" tabindex="-1" onfocus="this.blur()" type="text">
</div>
</td>
<td class="row">
<div class="col-md-8">
<input id="brochureItems_0__retail" class="form-control text-box single-line" data-val="true" data-val-number="The field Retail must be a number." data-val-required="The Retail field is required." name="brochureItems[0].retail" type="text">
</div>
</td>
<td class="remove"><span class="glyphicon glyphicon-remove removeRow"></span></td>
</tr>
</tbody>
I can only see that in the inspector. Source code shows an empty div where the table is supposed to go.
I don't think it matters, but that addBlurEvent function is getting called in the success of an ajax call. Here is the first function that gets called:
function loadItems() {
$.ajax({
url: '#Url.Action("_BrochureItems", "Brochure")',
type: 'POST',
data: { model: #Html.Raw(Json.Encode(#Model.brochureItems)) },
success: function (results) {
$("#itemList").html(results);
addBlurEvent();
},
error: function (request, status, error) {
displayError("Error", request.responseText);
}
});
}
Finally figured it out. I figured there must be a way because my other events in that function were working, just not that focus event. Ended up finding this SO Q&A which solved my issue: jquery focus back to the same input field on error not working on all browsers
Essentially, I had to set a timeout on the focus. So here is the code to do that:
setTimeout(function() { itemID.focus(); }, 50);
Remove the () around your function.
Issues with the siblings I made assumptions
Some code is useless and I commented it out.
Some code is "not present" in your example so I commented out references to that.
I made some assumptions that you wanted to focus the "cell" in the same TD row referenced by the "td" with a .row class.
function addBlurEvent() {
$("#brochureItems").on("blur", ".item-ID", function(e) {
var itemID = $(this);
var itemIDVal = $.trim(itemID.val());
if (itemIDVal != "") {
var item = "";
/* $.each(window.listOfItems, function(i, v) {
if (v.No.search(itemIDVal) != -1) {
item = v.Description;
return;
}
});
*/
if (item != "") {
// only one input in a cell (td)
// itemID.parent('.row').siblings(".item-desc").find("input").first().val(item);
itemID.parent('.row').siblings(".item-desc").find("input").val(item);
// no siblings of the inputs parent div exist in the TD cell
itemID.parent('.row').siblings(":last").find("input").first().focus();
} else {
//slideDownMsg("Item: " + itemIDVal + " not found.");
//slideUpMsg(3000);
itemID.focus();
}
} else {
itemID.parent('.row').siblings(".item-desc").find("input").val("");
itemID.parent('.row').siblings().last().find("input").val("")
}
});
$(".removeRow").on('click', function() {
$(this).closest("tr").remove();
});
}
Reference fiddle: https://jsfiddle.net/xL8wh3qo/
See this updated fiddle where I show examples of how to save a table row, clone it and then allow you to add new rows to your table from that. Even if all the rows are removed, you can add a new one from the saved clone, with proper id's based on your original row: https://jsfiddle.net/DTcHh/27778/
Related
I have made a form with dynamic table, and when the form is filled up, on button click, values from all fields will be inserted in one field with comma separated. The problem is that I don't know how to check if field is empty, if it then insert data, else update data in that input field.
This is my html code
<table>
<tbody>
<tr>
<td><input type="text" name="name"></td>
<td><button class="remove">-</button></td>
</tr>
<tr>
<td><input type="text" name="name"></td>
<td><button class="remove">-</button></td>
</tr>
</tbody>
</table>
<button id="addRow">+ Add</button>
<button id="getValues">Get Values</button>
<br/><br/><br/>
<input type="text" id="myMainPageInput" />
And this is jquery
var html = '<tr><td><input type="text" name="name"></td><td><button class="remove">-</button></td></tr>';
$(function() {
$('tbody').sortable();
$('#addRow').click(function(){
$('tbody').append(html);
});
$(document).on('click', '.remove', function() {
$(this).parents('tr').remove();
});
$('#getValues').click(function(){
var values = [];
if ($('input[name="name"]').val().length != 0){
$('input[name="name"]').each(function(i, elem){
$("#myMainPageInput").val(($("#myMainPageInput").val() + ', ' + $(elem).val()).replace(/^, /, ''));
});
}
});
});
This makes me duplicates everytime when I click on button.
Think of it differently: Since you are checking whether if it's empty or not empty, and proceed with the logic in any case (that's how I understood it, correct me if I'm wrong), then just empty the field entirely before populating it.
$('#getValues').click(function(){
$('input[name="name"]').val('');
var values = [];
$('input[name="name"]').each(function(i, elem){
$("#myMainPageInput").val(($("#myMainPageInput").val() + ', ' + $(elem).val()).replace(/^, /, ''));
});
});
Need help to solve a JavaScript problem.
i am working on an invoice in which i want to add more values to quantity field.
i am trying with script given in JSFiddle.
The problem is when i click on edit , it should popup a dialog box and by entering data in add field it should be added to current quantity of a specific item.
https://jsfiddle.net/programmer/LLmrp94y/16/
JS script
$(document).on('change', '.addQty', function () {
id_arr = $(this).attr('id');
id = id_arr.split("_");
add = $('#add_'+id[1]).val();
qty = $('#quantity_'+id[1]).val();
if (add != '' && typeof (add) != "undefined") {
$('#add_'+id[1]).val();
added = parseFloat(qty) + parseFloat(add);
$('#qtY_'+id[1]).val(added);
priceAfter = $('#price_'+id[1]).val();
$('#Total_'+id[1]).val((parseFloat(priceAfter) * parseFloat(added)).toFixed(2));
} else {
$('#quantity_'+id[1]).val(qty);
$('#Total_'+id[1]).val((parseFloat(price) * parseFloat(qty)).toFixed(2));
}
});
I made it work by doing the following :
adding an id to your edit buttons, so we can retrieve the id of the line currently being edited
replacing your 'onchange' function by a addQuantity function that takes a parameter : the id of the line being edited.
fixing a couple issues with the ids used in the code written to calculate the new quantity and the new price
Also, I replaced your php code by hard coded ids. You're going to have to replace them.
EDIT : Since you don't want to show the current quantity in the dialog, I had to change the logic and update the table after close has been clicked. Otherwise it caused too many issues. Hope you like it.
$(document).ready(function() {
calculateEachItemSubCost();
});
function calculateEachItemSubCost() {
var qtys = document.getElementsByClassName('quantity');
var price = document.getElementsByClassName('price');
var item_costs = document.getElementsByClassName('totalLinePrice');
for (var i = 0; i < item_costs.length; ++i) {
item_costs[i].value = parseFloat(qtys[i].value) * parseFloat(price[i].value).toFixed(2);
}
}
/* new function that replaces your 'onchange' listener. It handles the adding of a quantity on a given line, identified by the id parameter */
function addQuantity(id) {
var add, added, priceAfter;
add = $('#addedQuantity').val();
console.log("Adding " + add + " on line " + id);
if (add != '' && typeof add != "undefined") {
;
added = parseInt($('.add').val()) + parseInt($('#quantity_' + id).val())
$('#quantity_' + id).val(added);
priceAfter = $('#price_' + id).val();
$('#total_' + id).val((parseFloat(priceAfter) * parseFloat(added)).toFixed(2));
} else {
$('#quantity_' + id).val(qty);
$('#Total_' + id).val((parseFloat(price) * parseFloat(qty)).toFixed(2));
}
}
$(document).on('click', '.editnow', function(event) {
var lineId, quantityField;
// retrieving the id of the line that was clicked on
lineId = event.target.id.split("_")[1];
quantityField = $("#quantity_" + lineId);
$(".add").val("");
$("#edit").dialog({
show: "fold",
hide: "fold",
modal: true,
title: "Edit",
zIndex: 10000,
close: function(event, ui) {
addQuantity(lineId);
$(this).hide();
}
});
});
#edit{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/ui-lightness/jquery-ui.css"/>
<!DOCTYPE html>
<!-- Begin page content -->
<h1 class="text-center title">Invoice</h1>
<table>
<thead>
<tr>
<th width="38%">Item Name</th>
<th width="15%">Price</th>
<th width="15%">Quantity</th>
<th width="15%">Total</th>
<th width="15%">Edit</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value="samsung galaxy s6" id="itemName_1" ></td>
<td><input type="number" value="500" id="price_1" class="price"></td>
<td><input type="number" value="1" id="quantity_1" class="quantity"></td>
<td><input type="number" value="" id="total_1" class="totalLinePrice"></td>
<td><button type="button" class="editnow" id="edit_1"> Edit </button></td>
</tr>
<tr>
<td><input type="text" value="samsung galaxy s7" id="itemName_2" ></td>
<td><input type="number" value="700" id="price_2" class="price"></td>
<td><input type="number" value="1" id="quantity_2" class="quantity"></td>
<td><input type="number" value="" id="total_2" class="totalLinePrice"></td>
<td><button type="button" class="editnow" id="edit_2"> Edit </button></td>
</tr>
</tbody>
</table>
<div id="edit">
<table>
<tr>
<th>Add</th>
</tr>
<tr>
<td><input type="number" class="add" id="addedQuantity"></td>
</tr>
</table>
</div>
Your updated JSFiddle
I have edited it, but it does not work because of the php values not working, of course. I've added id to Edit buttons, and getting value from dialog. Based on the button id, you can enter value to corresponding quantity field
<button type="button" id="edit_<?php $i; ?>" class="editnow"> Edit </button>
Yes: function () {
var id = $(this).attr('id');
id = id.substring(id.indexOf('_')+1);
alert($('#quantityVal').val()); // just check the value
$('#quantity_'+id).val($('#quantityVal').val());
$(this).dialog("close");
},
Edit dialog number field
<td><input type="number" class="add" id="quantityVal"></td>
https://jsfiddle.net/LLmrp94y/12/
I have an HTML table with a date input field which currently runs an AJAX script when the date is modified. This is working well, but I now need another version of the script that acts on all table rows on the page to save the user from having to enter the date for each table row (there could be 20 on the page).
I've created another input for marking all the rows but stumped as to how to implement this. Ideally I'd like to pass an array of the table row IDs (e.g. id="61851") to a new script which calls a PHP script that handles the backend updating.
Here's my table:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/locales/bootstrap-datepicker.uk.min.js"></script>
<div class="col-md-8">
<h1>Items List</h1>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="col-md-6">
<table class="table table-bordered">
<tr>
<td>Flag All Received:</td>
<td><input type="text" class="form-control datepicker" name="dateReceivedAll" id="dateReceivedAll" data-date-format="dd/mm/yyyy" placeholder="Date Received"></td>
<td class="text-center">
<button type="submit" class="btn btn-success">Date Received All</button>
</td>
</tr>
</table>
</div>
<!-- /.col-md-6-->
<div class="col-md-6">
</div>
<!-- /.col-md-6-->
</div>
<!-- /.col-md-8-->
<div class="col-md-4">
</div>
<!-- /.col-md-4-->
</div>
<!-- /.row-->
<div>
<br />
<table class="table table-condensed table-striped table-bordered">
<thead>
<th class="text-center" scope="col">Item Tag</th>
<th class="text-center" scope="col">Serial Number</th>
<th class="text-center" scope="col">Received Date</th>
</thead>
<tbody>
<tr id="61851">
<td>61851</td>
<td>DTZ452432DDF</td>
<td id="61851"><input type="text" id="61851" class="form-control datepicker" autocomplete="off" placeholder="Date Rec'd" data-date-format="dd/mm/yyyy" name="dateReceived" value=""></td>
</tr>
<tr id="61852">
<td>61852</td>
<td>GZF2452542DA</td>
<td id="61852"><input type="text" id="61852" class="form-control datepicker" autocomplete="off" placeholder="Date Rec'd" data-date-format="dd/mm/yyyy" name="dateReceived" value=""></td>
</tr>
<tr id="61853">
<td>61853</td>
<td>TRA3241234ZZ</td>
<td id="61853"><input type="text" id="61853" class="form-control datepicker" autocomplete="off" placeholder="Date Rec'd" data-date-format="dd/mm/yyyy" name="dateReceived" value=""></td>
</tr>
</tbody>
</table>
</div>
and here's the current script that runs when you modify an individual date in the last column:
$(document).ready(function() {
$(".form-control.datepicker").change(function() {
var recid = $(this).closest('td').attr('id');
var dateReceived = $(this).val();
// Create a reference to $(this) here:
$this = $(this);
$.post('updateItem.php', {
recid: recid,
dateReceived: dateReceived
}, function(data) {
data = JSON.parse(data);
if (data.error) {
var ajaxError = (data.text);
var errorAlert = 'There was an error updating the Date Received - ' + ajaxError + '. Please contact the Help Desk';
$this.closest('td').addClass("has-error");
$("#dateReceivedErrorMessage").html(errorAlert);
$("#dateReceivedError").show();
return; // stop executing this function any further
} else {
$this.closest('td').addClass("has-success")
$this.closest('td').removeClass("has-error");
}
}).fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an error updating the Date Received - AJAX request error. HTTP Status: ' + httpStatus + '. Please contact the Help Desk';
$this.closest('td').addClass("has-error");
$("#dateReceivedErrorMessage").html(ajaxError);
$("#dateReceivedError").show();
});
});
});
I've added the Date Received All button and separate input field to capture the date all items were received, just not sure how to have that button trigger a similar version of the current JS but this time pass an array of all the id's?
change your change event , initialize event as per below method.
$(document).on("change",".form-control.datepicker",function(){
var recid = $(this).closest('td').attr('id');
var dateReceived = $(this).val();
// Create a reference to $(this) here:
$this = $(this);
$.post('updateItem.php', {
recid: recid,
dateReceived: dateReceived
}, function(data) {
data = JSON.parse(data);
if (data.error) {
var ajaxError = (data.text);
var errorAlert = 'There was an error updating the Date Received - ' + ajaxError + '. Please contact the Help Desk';
$this.closest('td').addClass("has-error");
$("#dateReceivedErrorMessage").html(errorAlert);
$("#dateReceivedError").show();
return; // stop executing this function any further
} else {
$this.closest('td').addClass("has-success")
$this.closest('td').removeClass("has-error");
}
}).fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an error updating the Date Received - AJAX request error. HTTP Status: ' + httpStatus + '. Please contact the Help Desk';
$this.closest('td').addClass("has-error");
$("#dateReceivedErrorMessage").html(ajaxError);
$("#dateReceivedError").show();
});
});
$('#sucess-btn').click(function(){
var ans = $('.table-condensed>tbody>tr').map(function(c,i,a){
return $(i).attr('id');
});
//ans is an array with numbers
});
Add this to your click event and ans array will have the IDs of the rows of the table. Add IDs to both table and the button and it will be easier to select the elements from the DOM.
Starting off there is a append button that generates a row with 1 select box, 1 inputbox, and 4 checkboxes. The limit of adding this would be 1-10 rows at max. I have no idea how to make a jquery validation using for example http://formvalidation.io/ - or a standalone jquery code. The rules I would like to apply:
If the role chosen is user (not an admin) , I must validate that there is at least one checkbox checked and the user doesn't appears twice in the selections
The thing is I don't even know where to start from, can you point me any hints?
Live example :: http://jsfiddle.net/Yy2gB/131/
Append method onClick
$(document).ready(function(){
var obj = {"1":"Admin istrator","2":"User2"};
//$('.selectpicker').selectpicker();
$(".addCF").click(function(){
count = $('#customFields tr').length + 1;
var sel = $('<select name="user'+count+'">');
for(key in obj){
// The key is key
// The value is obj[key]
sel.append($("<option>").attr('value',key).text(obj[key]));
}
$('.selectpicker').selectpicker();
$("#customFields").append('<tr><td>'+sel[0].outerHTML
+'</td><td><input class="form-control" class="valid_role"'
+' data-fv-field="emails" type="text" name="role'+count
+'" /></td><td><input type="checkbox" class="mycheckbox"'
+' name="can_edit'+count+'"></td><td><input type="checkbox" '
+'class="mycheckbox" name="can_read'+count+'"></td><td><input '
+'type="checkbox" class="mycheckbox" name="can_execute'+count+'">'
+'</td><td><input type="checkbox" class="mycheckbox" '
+'name="is_admin'+count+'"></td><td><a href="javascript:void(0);"'
+'class="remCF">Remove</a></td></tr>');
$('.mycheckbox').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue'
});
$('.selectpicker').selectpicker();
});
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});
HTML Form
<div class="col-md-12 col-lg-12">
<table class="table table-user-information" id="customFields">
<thead>
<tr>
<th class="standardTable_Header">User</th>
<th class="standardTable_Header">Role</th>
<th class="standardTable_Header">
<span title="administrator projektu">Can read</span>
</th>
<th class="standardTable_Header">
<span title="uprawnienie do edycji danych projektu">
edit
</span>
</th>
<th class="standardTable_Header">
<span title="uprawnienie do odczytu danych projektu oraz przypisanych do niego zadaĆ">
excute
</span>
</th>
<th class="standardTable_Header">
<span title="uprawnienie do edycji danych projektu">
admin
</span>
</th>
</tr>
</thead>
<tbody>
<button type="button" class="btn btn-default addCF">
Append
</button>
</div>
</tbody>
</table>
Using this jQuery Validation Plugin and through this demo, We could do the following:
Assumption: Roles check boxes must have at least one checked if - and only if - the select tag have the value User2
1- wrap your table with form tag that has a submit button:
<div class="col-md-12 col-lg-12">
<form id="myform">
<table class="table table-user-information" id="customFields">
...
</table>
<input type="submit" value="submit" />
</form>
</div>
2- We need to edit the checkboxes html to make them all have the same name but with different values, for example:
<input type="checkbox" class="mycheckbox" name="ourRoles" value="can_edit' ...>
<input type="checkbox" class="mycheckbox" name="ourRoles" value="can_read' ...>
and so on.
3- Add the following script:
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("#myform").validate({
rules: {
ourRoles: {
required: function () {
if ($("select[name=user2]").val() == 2) {
return true;
} else {
return false;
}
}
}
}
});
See all together with this fiddle
I have a script that should automatically change the value when drop down list selection is changed, and it works first time I change the value, but second time it does not work (after I try to select different value from the one I selected previously)
Here is the HTML:
<input id="search" placeholder="Search..." type="text"/>
<label for="showbrand" class="filter">Brand:<select id="showbrand" data-bind=''>
<option value="">--select--</option>
<option value="">All</option>
</select></label>
<label for="showfrom" class="filter">From:<input type="date" id="showfrom"></label>
<label for="showto" class="filter">To:<input type="date" id="showto"></label>
<a id="filterList" class="btn btn-primary pull-right" onclick="clickFilter();">Find</a><table id="dataTable" class="table table-condensed table-bordered">
<thead>
<tr>
<th>Campaign</th>
<th>Brand</th>
<th>Starts On</th>
<th>Ends On</th>
<th>Files</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="msg"></div>
JS:
$("#showbrand").change(function(){
var info = new Array();
info[0] = $("#showbrand").val();
if($("#showfrom").val() !== '' &&
$("#showto").val() !== ''){
info[1] = 'yes';
}
else{
info[1] = 'no';
}
info[2] = $("#showfrom").val();
info[3] = $("#showto").val();
info[4] = $("#search").val();
listCampaignsFiltered(info, 'dataTable', 0);
});
unction listCampaignsFiltered(info, tableName, limit){
var params = "&brand="+info[0]+
"&daterange="+info[1]+
"&from="+info[2]+
"&to="+info[3]+
"&limit="+limit+
"&search="+info[4];
$.getJSON(LOCAL_URI+"?action=campaignfiltered"+params, function(result) {
//console.log(JSON.stringify(result));
$('#'+tableName+" tbody").html('');
if(result.length > 0){
$("#msg").html(result.length+ " Records found.");
$.each(result, function(){
var $tr = '<tr><td>'+ this.campaign + "</td><td>"+
this.brandName+"</td><td>"+this.startson+
"</td><td>"+ this.endson +"</td></tr>";
$('#'+tableName+" tbody").append($tr);
});
}
else{
$("#msg").html('No records found.');
}
});
}
For your select element to change, you might need distinct values, otherwise no matter what you choose as your option, it'll always have the same value.
I've never setup a select element without values so I'm not 100% sure this is your issue. Please let me know if this happens to be the issue, otherwise I'll remove the answer.
Also, your JS needs a closing ) to be valid.
Yes you should assign the value in dropdown and also correct your syntax in jquery.
I think below code will help you
<script type="text/javascript" language="javascript" >
$(document).ready(function () {
$("#showbrand").change(function () {
var info = new Array();
info[0] = $("#showbrand").val();
alert(info[0]);
});
});
</script>
<label for="showbrand" class="filter">Brand:
<select id="showbrand" data-bind=''>
<option value="1">--select--</option>
<option value="2">test</option>
<option value="3">All</option>
</select>
</label>