I have this sample http://jsfiddle.net/7aDak/927/ . I need to iterate through each table's each row's dropdown and textarea and build a string based on that . I must not use id's . How would I do it ? Thanks in advance .
Your code was almost set.. just needed minor fix.. See below,
DEMO: http://jsfiddle.net/7aDak/931/
$("#btnSave").click(function() {
$(".templateTable").each(function() {
//v-- Used $(this).find('tr') to get all tr from the selected table
$(this).find("tr").each(function() {
$this = $(this)
var email = $this.find("textarea").val();
var frequency = $this.find("select").val();
alert(email + '--' + frequency);
});
});
});
or As suggested by Rune
$("#btnSave").click(function() {
$(".templateTable tr").each(function() {
$this = $(this)
var email = $this.find("textarea").val();
var frequency = $this.find("select").val();
alert(email + '--' + frequency);
});
});
this "tr.item" is not a real selector.
You need to split them into two separate chained selections:
$(this).find("tr.item")
here's the answer:
http://jsfiddle.net/7aDak/935/
change in html: you need to add a class 'select' to all your select elements.
Rest is in js code.
Related
I'm not the best at using jQuery, but I do require it to be able to make my website user-friendly.
I have several tables involved in my website, and for each the user should be able to add/delete rows. I created a jquery function, with help from stackoverflow, and it successfully added/deleted rows. Now the only problem with this is the names for those input fields is slightly messed up. I would like each input field to be an array: so like name[0] for the first row, name[1] for the second row, etc. I have a bunch of tables all with different inputs, so how would I make jQuery adjust the names accordingly?
My function, doesn't work completely, but I do not know how to go about changing it.
My Jquery function looks like:
$(document).ready(function() {
$("body").on('click', '.add_row', function() {
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
var clone = tr.clone();
clone.find("input").val('');
clone.find("select").val('');
clone.find('input').each(function(i) {
$(this).attr('name', $(this).attr('name') + i);
});
clone.find('select').each(function(i) {
$(this).attr('name', $(this).attr('name') + i);
});
tr.after(clone);
});
$("body").on('click', '.delete_row', function() {
var rowCount = $(this).closest('.row').prev('table').find('tr.ia_table').length;
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
if (rowCount > 1) {
tr.remove();
};
});
});
I also created a jsFiddle here: https://jsfiddle.net/tareenmj/err73gLL/.
Any help is greatly appreciated.
UPDATE - Partial Working Solution
After help from a lot of users, I was able to create a function which does this:
$("body").on('click', '.add_row', function() {
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
var clone = tr.clone();
clone.find("input").val('');
clone.find("select").val('');
clone.find('input').each(function() {
var msg=$(this).attr('name');
var x=parseInt(msg.split('[').pop().split(']').shift());
var test=msg.substr(0,msg.indexOf('['))+"[";
x++;
x=x.toString();
test=test+x+"]";
$(this).attr('name', test);
});
clone.find('select').each(function() {
var msg1=$(this).attr('name');
var x1=parseInt(msg1.split('[').pop().split(']').shift());
var test1=msg1.substr(0,msg1.indexOf('['))+"[";
x1++;
x1=x1.toString();
test1=test1+x1+"]";
$(this).attr('name', test1);
});
tr.after(clone);
});
A working jsFiddle is here: https://jsfiddle.net/tareenmj/amojyjjn/2/
The only problem is that if I do not select any of the options in the select inputs, it doesn't provide me with a value of null, whereas it should. Any tips on fixing this issue?
I think I understand your problem. See if this fiddle works for you...
This is what I did, inside each of the clone.find() functions, I added the following logic...
clone.find('input').each(function(i) {
// extract the number part of the name
number = parseInt($(this).attr('name').substr($(this).attr('name').indexOf("_") + 1));
// increment the number
number += 1;
// extract the name itself (without the row index)
name = $(this).attr('name').substr(0, $(this).attr('name').indexOf('_'));
// add the row index to the string
$(this).attr('name', name + "_" + number);
});
In essence, I separate the name into 2 parts based on the _, the string and the row index. I increment the row index every time the add_row is called.
So each row will have something like the following structure when a row is added...
// row 1
sectionTB1_1
presentationTB1_1
percentageTB1_1
courseTB1_1
sessionTB1_1
reqElecTB1_1
// row 2
sectionTB1_2
presentationTB1_2
percentageTB1_2
courseTB1_2
sessionTB1_2
reqElecTB1_2
// etc.
Let me know if this is what you were looking for.
Full Working Solution for Anyone Who needs it
So after doing loads and loads of research, I found a very simple way on how to do this. Instead of manually adjusting the name of the array, I realised that the clone method will do it automatically for you if you supply an array as the name. So something like name="name[]" will end up working. The brackets without any text has to be there. Explanation can't possible describe the code fully, so here is the JQuery code required for this behaviour to work:
$(document).ready(function() {
$("body").on('click', '.add_row', function() {
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
var clone = tr.clone();
clone.find("input").val('');
tr.after(clone);
});
$("body").on('click', '.delete_row', function() {
var rowCount =
$(this).closest('.row').prev('table').find('tr.ia_table').length;
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
if (rowCount > 1) {
tr.remove();
};
});
});
A fully working JSfiddle is provided here: https://jsfiddle.net/tareenmj/amojyjjn/5/
Just a tip, that you have to be remove the disabled select since this will not pass a value of null.
So I downloaded TinyNav.js which helps me with my websites menu and can't figure out how to get the element ID from the "a" tag. I have modified TinyNav.js in one spot here.
The code is right here:
https://github.com/viljamis/TinyNav.js/blob/master/tinynav.js
I need help with line 61.
window.location.href = $(this).val();
I changed this line to
window.location.onClick = (A javascript function call which expects a string)
The string in this case is what I need help on. I need to get the SELECTED items ID, and I can't seem to find a way to do that. The
$(this).val();
returns to me the href of the selected item I clicked on in my menu but again, I want just the selected element's ID. How do I get this value?
The <option> elements are created dynamically in the tinyNav script on line 40:
options += '<option value="' + $(this).attr('href') + '">';
They only have a value attribute, no IDs.
I'm assuming that your ID values are inside you <a> tags, such as:
About
You can grab the IDs and put them into your options like this:
options += '<option value="' + $(this).attr('href') + '" id="' + $(this).attr('id') + '">';
Then you can get the ID inside the change function.
Change this (lines 60-62):
$select.change(function () {
window.location.href = $(this).val();
});
To this:
$select.change(function () {
console.log($(this).find(":selected").attr('id'));
window.location.href = $(this).val();
});
The value of $(this) is the select element that is being changed. Then you can use .find(":selected") to get the selected option element, and finally .attr('id') to get the ID attribute.
Here is a jsfiddle: https://jsfiddle.net/t72wdcwc/41/
window.location.onClick is incorrect. Javscript is case-sensitive and uses onclick, with no camelCase. You can do the following:
window.location.onclick = function() {
yourFunction($(this).attr("id"));
}
function yourFunction(id) {
alert("You clicked " + id);
}
I'm going to append multiple values from an input, curious on how I can dry the append code. Possibly into a function, thanks!
var $inputFirst = $('input:first').val();
var $inputSecond = $('input:second').val();
$('ul').append('<li>' + $inputFirst + '</li>');
$('ul').append('<li>' + $inputSecond+ '</li>');
This should work for you
$(':input').each(function(i){
$('ul').append('<li>'+$(':input').eq(i).val()+'</li>')
})
Assuming you have same number of input and li. You can iterate through the li and append the corresponding input value it.
inputs = $('input');
$('ul li').each(function(){
$this).append(inputs.eq($this).index()));
});
Note As a additional note you are using tag that will effect the whole page. It might include the element you do not want to be part of this. So use class or some other attributes to access both li and input elements.
inputs = $('.class-of-input');
$('.class-of-ul li').each(function(){
$this).append(inputs.eq($this).index()));
});
hey i have created example for you on jsfiddle:-
$(document).ready(function() {
$("#createLI").click(function() {
var lis = "";
$(".forLI").each(function() {
var vl = $(this).val();
lis += "<li>" + vl + "</li>"
});
$("ul").append($(lis));
});
});
working example link:http://jsfiddle.net/BtkCf/166/
we are using class to filter the input so it will select all the inputs while creating LI tags.
in above example you can have any number of input boxes.
just provide a class 'forLI' to input boxes it will append there text values to ul as li.
we can not select value like this $('input:second').val(); you can use $('input:eq(1)').val();
thanks
I am currently attempting to write a function that applies unique ids to list item dynamically by ticking checkboxes, though I have encountered a problem, when appending the unique id to the list item I get the following error message in the console:
Uncaught TypeError: Object SpTU 4, 183:false<br /> has no method 'append'
Here is the code that is causing the error:
strng += name+":"+val+"<br />";
var i = 1;
strng.append($({ type: "text", id:+i }));
I need help with this quickly so any help would be greatly appreciated!
Thanks in advance
-------EDIT----------
Here is the whole function so it is easier to understand, I am new to programming to it may be very messy and unproffesional.
var dataToShow = {};
function check(tickbox){
dataToShow[tickbox.value] = tickbox.checked == true;
showDataOnScreen(dataToShow);
function showDataOnScreen(dataToShow){
var $strng = "";
jQuery.each(dataToShow,function(name,val){
$strng += name+":"+val+"<br />";
var i = 1;
$strng.append($({ type: "text", id:+i }));
});
jQuery("#list").html(strng);
Ensure that strng is a JQUERY object, assuming you are using JQUERY
If you are trying to build a list of checked items, I would go about it this way.
// create an array to store the checked items
var checkedItems = new Array();
// loop through the checked check boxes contained in the list element
// and add them to the array
$("#list :checked").each(function (){
var item = { name: $(this).attr("name"), value: $(this).val() };
checkedItems.push(item);
});
Or, even better, if you plan on displaying the results in a different element, you can cut out the array.
// loop through the checked check boxes contained in the list element
// and add them to a different element
$("#list :checked").each(function (){
var item = "<div>"+ $(this).attr("name") + ": " + $(this).val() + "</div>";
$("#selectedList").append(item);
});
Here's a working example on jsFiddle.
References:
Array: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
jQuery each(): http://api.jquery.com/jQuery.each/
jQuery :checked selector: http://api.jquery.com/checked-selector/
jQuery append(): http://api.jquery.com/append/
i'm trying to make a live search for my mobile website, I don't want to query the database every time a user type a letter so I created a ordered list with all the names that can be searched for and i'm looping through it with jquery, problem is that I have 3300 names and it's freezing the browser when it searches through them, can anyone give me a tip about better ways to do it? here is my code:
$(document).ready(function(){
$("input#search").keyup(function(){
var filter = $(this).val(), count = 0;
var html = "";
$("ol.pacientes li").each(function(){
var nome_paciente = $(this).text();
if(nome_paciente.indexOf(filter.toUpperCase()) != -1){
html = html + " " + nome_paciente;
}
$('#pacientes_hint').html(html);
});
Use the jQuery autocomplete version. You can load an array with all your names and pass it in to autocomplete, which will work on the fly.
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
You could change your each to:
var text = $("ol.pacientes li:contains(\""+filter.toUpperCase()+"\")").map(function() {
return $(this).text();
}).join(' ');
$('#pacientes_hint').text(text);
Besides being shorter, the only improvement will be setting the contents of $('#pacientes_hint') only at the end, which could help.
Let me know if you need a more creative solution.
First of all, you could move #pacientes_hint outside the each function.
$(document).ready(function(){
$("input#search").keyup(function(){
var filter = $(this).val(), count = 0;
var html = "";
$("ol.pacientes li").each(function(){
var nome_paciente = $(this).text();
if(nome_paciente.indexOf(filter.toUpperCase()) != -1){
html = html + " " + nome_paciente;
} // end if
}); // end each
$('#pacientes_hint').html(html);
Then, you can define ol.pacientes as a variable before the keyup handler, so it doesn't look for it everytime and in the each function, search inside the variable:
$(document).ready(function(){
var pacientes_list = $("ol.pacientes");
var pacientes_hint = $("#pacientes_hint");
$("input#search").keyup(function(){
...
$("li", $(pacientes_list)).each(function(){ // search in the container
...
}); // end each
$(pacientes_hint).html(html);