I am using Data Table in jquery. So i passed one input type text box and passed the single id. This data table will take a multiple text box. i will enter values manually and pass it into the controller. I want to take one or more text box values as an array..
The following image is the exact view of my data table.
I have marked red color in one place. the three text boxes are in same id but different values. how to bind that?
function UpdateAmount() {debugger;
var id = "";
var count = 0;
$("input:checkbox[name=che]:checked").each(function () {
if (count == 0) {
id = $(this).val();
var amount= $('#Amount').val();
}
else {
id += "," + $(this).val();
amount+="," + $(this).val(); // if i give this i am getting the first text box value only.
}
count = count + 1;
});
if (count == 0) {
alert("Please select atleast one record to update");
return false;
}
Really stuck to find out the solution... I want to get the all text box values ?
An Id can only be used once; use a class, then when you reference the class(es), you can loop through them.
<input class="getValues" />
<input class="getValues" />
<input class="getValues" />
Then, reference as ...
$(".getValues")
Loop through as ...
var allValues = [];
var obs = $(".getValues");
for (var i=0,len=obs.length; i<len; i++) {
allValues.push($(obs[i]).val());
}
... and you now have an array of the values.
You could also use the jQuery .each functionality.
var allValues = [];
var obs = $(".getValues");
obs.each(function(index, value) {
allValues.push(value);
}
So, the fundamental rule is that you must not have duplicate IDs. Hence, use classes. So, in your example, replace the IDs of those text boxes with classes, something like:
<input class="amount" type="text" />
Then, try the below code.
function UpdateAmount() {
debugger;
var amount = [];
$("input:checkbox[name=che]:checked").each(function () {
var $row = $(this).closest("tr");
var inputVal = $row.find(".amount").val();
amount.push(inputVal);
});
console.log (amount); // an array of values
console.log (amount.join(", ")); // a comma separated string of values
if (!amount.length) {
alert("Please select atleast one record to update");
return false;
}
}
See if that works and I will then add some details as to what the code does.
First if you have all the textbox in a div then you get all the textbox value using children function like this
function GetTextBoxValueOne() {
$("#divAllTextBox").children("input:text").each(function () {
alert($(this).val());
});
}
Now another way is you can give a class name to those textboxes which value you need and get that control with class name like this,
function GetTextBoxValueTwo() {
$(".text-box").each(function () {
alert($(this).val());
});
}
Related
I want to store the multiple id to hidden field.
So value able to bind to controller.
<form:hidden id="ids" path="ids" value="${ids }"/>
When click button delete will call jquery to delete row.
var deleteIds = [];
$("#deleteRow").on('click', function() {
deleteIds = $('.case:checkbox:checked').val();
$('.case:checkbox:checked').parents("tr").remove();
$('#ids').val(deleteIds);
});
My question is
How to set the value into ids?
Thank You.
The tag from doesn't have the attribute value. You can check the attributes for the form tag here.
However, you can use jQuery to modify custom attributes. Here's a working fiddle:
var deleteIds = [];
deleteIds = ["1","2","3","4"];
$('#ids').attr("value",deleteIds);
alert($('#ids').attr("value"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="ids" path="ids" value="${ids }"/>
By creating multiple <form:hidden/>, you can get what you want. I assume you when you click #deleteRow, table rows is deleted and you submit form of these ids to server, so we can make it by follow.
Cause I even don't know your html structure, so I've just tried to modify your script, may help you;)
var deleteIds = [];
$("#deleteRow").on('click', function() {
$('#ids').remove();
deleteIds = $('.case:checkbox:checked').val();
$('.case:checkbox:checked').parents("tr").remove();
for (var i = 0; i < deleteIds.length; i++) {
// formId should be replaced to your form id
$('#formId').append('<form:hidden id="ids" path="ids" value="' + deleteIds[i] +'"/>');
}
// $('#formId').submit(); comment this line, cause there is another button to submit form.
});
I able to set the multiples value to hidden field. Answer as below.
<form:hidden id="ids" path="ids" value="${ids }"/>
$("#deleteRow").on('click', function() {
var deleteIds = [];
$('.case:checkbox:checked').each(function(i){
if($('#ids').val() != ''){
deleteIds[i] = $('#ids').val() + "," + $(this).val();
}else{
deleteIds[i] = $(this).val();
}
});
$('#ids').attr("value",deleteIds);
});
The each(function(i)) will loop all the checkbox and store in array[], after that assign the array to hidden field.
I'm creating a Time table generating website as a part of my project and I am stuck at one point.
Using for loop, I am generating user selected text boxes for subjects and faculties. Now the problem is that I cannot get the values of those dynamically generated text boxes. I want to get the values and store it into array so that I can then later on store it to database
If I am using localstorage, then it sometimes shows NaN or undefined. Please help me out.
Following is my Jquery code
$.fn.CreateDynamicTextBoxes = function()
{
$('#DynamicTextBoxContainer, #DynamicTextBoxContainer2').css('display','block');
InputtedValue = $('#SemesterSubjectsSelection').val();
SubjectsNames = [];
for (i = 0; i < InputtedValue; i++)
{
TextBoxContainer1 = $('#DynamicTextBoxContainer');
TextBoxContainer2 = $('#DynamicTextBoxContainer2');
$('<input type="text" class="InputBoxes" id="SubjectTextBoxes'+i+'" placeholder="Subject '+i+' Name" style="margin:5px;" value=""><br>').appendTo(TextBoxContainer1);
$('<input type="text" class="InputBoxes" id="FacultyTextBoxes'+i+'" placeholder="Subject '+i+' Faculty Name" style="margin:5px;" value=""><br>').appendTo(TextBoxContainer2);
SubjectsNames['SubjectTextBoxes'+i];
}
$('#DynamicTextBoxContainer, #UnusedContainer, #DynamicTextBoxContainer2').css('border-top','1px solid #DDD');
}
$.fn.CreateTimeTable = function()
{
for (x = 0; x < i; x++)
{
localStorage.setItem("Main"+x, +SubjectsNames[i]);
}
}
I am also posting screenshot for better understanding
I understand you create 2 text boxes for each subject, one for subject, and second one for faculty. And you want it as a jQuery plugin.
First of all, I think you should create single plugin instead of two, and expose what you need from the plugin.
You should avoid global variables, right now you have InputtedValue, i, SubjectsNames, etc. declared as a global variables, and I believe you should not do that, but keep these variables inside you plugin and expose only what you really need.
You declare your SubjectNames, but later in first for loop you try to access its properties, and actually do nothing with this. In second for loop you try to access it as an array, but it's empty, as you did not assign any values in it.
Take a look at the snippet I created. I do not play much with jQuery, and especially with custom plugins, so the code is not perfect and can be optimized, but I believe it shows the idea. I pass some selectors as in configuration object to make it more reusable. I added 2 buttons to make it more "playable", but you can change it as you prefer. Prepare button creates your dynamic text boxes, and button Generate takes their values and "print" them in result div. generate method is exposed from the plugin to take the values outside the plugin, so you can do it whatever you want with them (e.g. store them in local storage).
$(function() {
$.fn.timeTables = function(config) {
// prepare variables with jQuery objects, based on selectors provided in config object
var numberOfSubjectsTextBox = $(config.numberOfSubjects);
var subjectsDiv = $(config.subjects);
var facultiesDiv = $(config.faculties);
var prepareButton = $(config.prepareButton);
var numberOfSubjects = 0;
prepareButton.click(function() {
// read number of subjects from the textbox - some validation should be added here
numberOfSubjects = +numberOfSubjectsTextBox.val();
// clear subjects and faculties div from any text boxes there
subjectsDiv.empty();
facultiesDiv.empty();
// create new text boxes for each subject and append them to proper div
// TODO: these inputs could be stored in arrays and used later
for (var i = 0; i < numberOfSubjects; i++) {
$('<input type="text" placeholder="Subject ' + i + '" />').appendTo(subjectsDiv);
$('<input type="text" placeholder="Faculty ' + i + '" />').appendTo(facultiesDiv);
}
});
function generate() {
// prepare result array
var result = [];
// get all text boxes from subjects and faculties divs
var subjectTextBoxes = subjectsDiv.find('input');
var facultiesTextBoxes = facultiesDiv.find('input');
// read subject and faculty for each subject - numberOfSubjects variable stores proper value
for (var i = 0; i < numberOfSubjects; i++) {
result.push({
subject: $(subjectTextBoxes[i]).val(),
faculty: $(facultiesTextBoxes[i]).val()
});
}
return result;
}
// expose generate function outside the plugin
return {
generate: generate
};
};
var tt = $('#container').timeTables({
numberOfSubjects: '#numberOfSubjects',
subjects: '#subjects',
faculties: '#faculties',
prepareButton: '#prepare'
});
$('#generate').click(function() {
// generate result and 'print' it to result div
var times = tt.generate();
var result = $('#result');
result.empty();
for (var i = 0; i < times.length; i++) {
$('<div>' + times[i].subject + ': ' + times[i].faculty + '</div>').appendTo(result);
}
});
});
#content div {
float: left;
}
#content div input {
display: block;
}
#footer {
clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<div id="header">
<input type="text" id="numberOfSubjects" placeholder="Number of subjects" />
<button id="prepare">
Prepare
</button>
</div>
<div id="content">
<div id="subjects">
</div>
<div id="faculties">
</div>
</div>
</div>
<div id="footer">
<button id="generate">Generate</button>
<div id="result">
</div>
</div>
im adding table row data using json response. here is my code
var i;
for (i = 0; i < result.length; i++) {
$.get('LoadserviceSplit', {
"sectcode" : result[i]
},
function (jsonResponse) {
if (jsonResponse != null) {
var table2 = $("#table_assign");
$.each(jsonResponse, function (key, value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['serviceId']);
rowNew.children().eq(1).text(value['title']);
rowNew.children().eq(2).html('<input type="text" id="date_set" name="date_set"/>');
rowNew.children().eq(3).html('<input type="text" id="date_set1" name="date_set1"/>');
rowNew.children().eq(4).html('<input type="text" id="date_set2" name="date_set2"/>');
rowNew.children().eq(5).html('<select class="status1" id="status1">');
rowNew.appendTo(table2);
});
}
});
var pass_unit_code = "001";
$.get('LoadDivisionCodeServlet', { //call LoadDivisionCodeServlet controller
unitCode : pass_unit_code //pass the value of "sample" to unitCode:
}, function (jsonResponse) { //json response
var select = $('#status1'); //select #status1 option
select.find('option').remove(); //remoev all item in #divcode option
$.each(jsonResponse, function (index, value) {
$('<option>').val(value).text(value).appendTo(select); //response from JSON in array value{column:value,column:value,column:value}
});
});
}
it works fine except the select tag part. only the first row of table have value. the rest has no value. i want all drop-down list inside the table has same value.. can anyone help me about this.
Take a look at
rowNew.children().eq(5).html('<select class="status1" id="status1">');
You're creating new select elements in a $.each and assigning the same id, that is status1 to all of them.
Then you're selecting the select element that has an id of status1 like
var select = $('#status1'); //select #status1 option
Therefore, only the first select element will be selected.
EDIT:
Your question is not completely clear.
However, this is how you can add different Id for select inside each of your <td>
Replace this
rowNew.children().eq(5).html('<select class="status1" id="status1">');
With something like
rowNew.children().eq(5).html('<select class="status1" id="status'+key+'">');
So this will have different Ids.
I have a list with about 10 000 customers on a web page and need to be able to search within this list for matching input. It works with some delay and I'm looking for the ways how to improve performance. Here is simplified example of HTML and JavaScript I use:
<input id="filter" type="text" />
<input id="search" type="button" value="Search" />
<div id="customers">
<div class='customer-wrapper'>
<div class='customer-info'>
...
</div>
</div>
...
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#search").on("click", function() {
var filter = $("#filter").val().trim().toLowerCase();
FilterCustomers(filter);
});
});
function FilterCustomers(filter) {
if (filter == "") {
$(".customer-wrapper").show();
return;
}
$(".customer-info").each(function() {
if ($(this).html().toLowerCase().indexOf(filter) >= 0) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
}
</script>
The problem is that when I click on Search button, there is a quite long delay until I get list with matched results. Are there some better ways to filter list?
1) DOM manipulation is usually slow, especially when you're appending new elements. Put all your html into a variable and append it, that results in one DOM operation and is much faster than do it for each element
function LoadCustomers() {
var count = 10000;
var customerHtml = "";
for (var i = 0; i < count; i++) {
var name = GetRandomName() + " " + GetRandomName();
customerHtml += "<div class='customer-info'>" + name + "</div>";
}
$("#customers").append(customerHtml);
}
2) jQuery.each() is slow, use for loop instead
function FilterCustomers(filter) {
var customers = $('.customer-info').get();
var length = customers.length;
var customer = null;
var i = 0;
var applyFilter = false;
if (filter.length > 0) {
applyFilter = true;
}
for (i; i < length; i++) {
customer = customers[i];
if (applyFilter && customer.innerHTML.toLowerCase().indexOf(filter) < 0) {
$(customer).addClass('hidden');
} else {
$(customer).removeClass('hidden');
}
}
}
Example: http://jsfiddle.net/29ubpjgk/
Thanks to all your answers and comments, I've come at least to solution with satisfied results of performance. I've cleaned up redundant wrappers and made grouped showing/hiding of elements in a list instead of doing separately for each element. Here is how filtering looks now:
function FilterCustomers(filter) {
if (filter == "") {
$(".customer-info").show();
} else {
$(".customer-info").hide();
$(".customer-info").removeClass("visible");
$(".customer-info").each(function() {
if ($(this).html().toLowerCase().indexOf(filter) >= 0) {
$(this).addClass("visible");
}
});
$(".customer-info.visible").show();
}
}
And an test example http://jsfiddle.net/vtds899r/
The problem is that you are iterating the records, and having 10000 it can be very slow, so my suggestion is to change slightly the structure, so you won't have to iterate:
Define all the css features of the list on customer-wrapper
class and make it the parent div of all the list elements.
When your ajax request add an element, create a variable containing the name replacing spaces for underscores, let's call it underscore_name.
Add the name to the list as:
var customerHtml = "<div id='"+underscore_name+'>" + name + "</div>";
Each element of the list will have an unique id that will be "almost" the same as the name, and all the elements of the list will be on the same level under customer-wrapper class.
For the search you can take the user input replace spaces for underscores and put in in a variable, for example searchable_id, and using Jquery:
$('#'+searchable_id).siblings().hide();
siblings will hide the other elements on the same level as searchable_id.
The only problem that it could have is if there is a case of two or more repeated names, because it will try to create two or more divs with the same id.
You can check a simple implementation on http://jsfiddle.net/mqpsppxm/
Here is my simple data
John Smith Individual 010987654
I have three textboxes and the above data will automatically insert in the first textbox of my web page.
My problem is
How can I make as soon as data is inserted in the textbox (means when textbox’s onchange event is fired)
First, javascript will find ‘tab’ space in this string
Second, if find ‘tab’ space in the string, javascript will press ‘tab’ key and insert data in the another text box.
Here's a plain old DOM-0 JavaScript solution, just for fun.
document.getElementById('the_form').onchange = function() {
var field = this[0];
var parts = field.value.split('\t');
for (var i = 0; field = this[i]; i++) {
field.value = parts[i] || '';
}
}
http://jsfiddle.net/vKaxP/
I thought you want to split those texts into different textboxes, so I got something like:
$("#a").change(function(){
var s = $(this).val();
if (s.match(/\t+/)) {
var a = s.split(/\t+/);
$('#a').val(a[0]);
$('#b').val(a[1]);
$('#c').val(a[2]);
}
});
if you type a b c into the first input box, press tab or enter, b and c would appear into other textboxes, repectively.
I use \s(space) for test in jsfiddle. You could just change it to \t for tab.
Here is prototype of what you need to do.
HTML:
<div>
<input id="a" />
</div>
<div>
<input id="b" />
</div>
JavaScript:
$('#a').on('change', function () {
var value = $(this).val();
// Test if string has a tab:
if (/\t/.test(value)) {
// Just set the value of the other text box
// And set focus:
// Using jQuery that would be:
$('#b').val(value).focus();
}
});
Working demo: http://jsfiddle.net/tkirda/XmArP/
If I correctly understand the question as "The server puts all the data into one field, tab separated, and I want to split it up into several textfields", then try this:
On load:
var fields = [$("#firstField"), $("#secondField"), $("#thirdField")];
var data = fields[0].val().split(/\t/);
for (var i = 0; i < 3; i++) {
fields[i].val(data[i]);
}