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/
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.
>
I got a problem, My Jquery runs fine for one selected item but when the multiple items are selected I start getting the values of unselected child. I only wanted the Selected Parent(station_group) and Child(Unit_group) checkboxes. Please Help my Current code.
$(document).on("click", "#searchButton",function() {
var InputString="-";
$.each($('input[name="Station_group"'),function(index,item){
if($(item).is('input:checked')){
var StationItem =$(this).val();
$.each($('input[name="Unit_group"'),function(index,item){
if($(item).is('input:checked')){
var unitItem = $(this).val();
$.each($('input[name="Alarm_group"'),function(index,item){
if($(item).is('input:checked')){
var alarmItem = $(this)[0].nextSibling.nodeValue;;
var resultString = StationItem.concat(","+unitItem+","+alarmItem+"|");
InputString=InputString+resultString;
};
});
};
});
};
});
});
After a lot of head hunting, i manage to find the answer to my own question.The logic needed to change instead of looping by parent-child. I decide to loop by selected child and then getting the parent value. Using the jquery parent and eq function I was able to find the needed values.
$.each($('input[name="Unit_group"'),function(index,item){
if($(item).is('input:checked')){
var unitItem = $(this).val();
var stationitem=$(this).parents('li').eq(1).find('input').val();
$.each($('input[name="Alarm_group"'),function(index,item){
if($(item).is('input:checked')){
var alarmItem = $(this)[0].nextSibling.nodeValue;;
var resultString = stationitem.concat(","+unitItem+","+alarmItem+"|");
InputString=InputString+resultString;
};
});
};
im trying to loop through a JSON object via Jquery. For some reason its not looping right.. It seems to be looping all the way to the end, But I would like to get each individually property in my object. Im using a For(var in) loop which loops through my object correctly but its a bit off.. MyAny help would be glady appreciated.. thanks so much!!! I can provide a quick link to my website that has mock up of the code if needed..
Ive also added more code and html via elements that using ..Hint*** Theres more if - conditional statements that checks for sounds_like,sounds_price... The first JSON Object works with no problem, its the second JSON object that im using with the pop over thats causing me trouble
<div class="overlay-bg">
<div id= "overlay" class="overlay-content">
<p>This is a popup!</p>
<button class="close-btn">Close</button>
</div>
</div>
$.getJSON("php/music_data.php",function(data){
$.each(data,function(key,obj){
for(var prop in obj){
// console.log("Property: " + prop + " key:" + obj[prop]);
if(prop === "sounds_like"){
results_div = document.getElementById("results");
music_div_container = document.createElement("div");
music_div_container.id = "music_data_container";
music_div_container.innerHTML = "<div id=\"sounds_like\">" + "Sounds Like: " + obj["sounds_like"] +"</div>";
results_div.appendChild(music_div_container);
var pop_up = document.createElement("a");
pop_up.href = "#";
pop_up.className = "show-popup";
pop_up.innerHTML = "Click";
music_div_container.appendChild(pop_up);
default_photo = document.createElement('div');
}
if(prop === "sound_desc"){
var sound_desc = document.createElement("div");
sound_desc.innerHTML = "<div id=\"sounds_desc\">" + obj["sound_desc"] +"</div>";
music_div_container.appendChild(sound_desc);
}
$.getJSON("php/music_data.php",function(data){
$.each(data,function(idx,obj){
$.each(obj,function(key,value){
$(".show-popup").click(function(event){
event.preventDefault();
$(".overlay-bg").show();
if(key === "sounds_like"){
/***Should be Beyonce,Drake,Nicki Minaj***/
/*****But my console is showing Nicki Minaj*******/
$(".overlay-content").html(value);
}
if(value === "sounds_desc"){
/***Should be Smooth, Wu tang Forever, Barbie***/
/*****But my console is showing Barbie*******/
$(".overlay-content").html(value);
}
$('.close-btn').click(function(){
$('.overlay-bg').hide(); /*** hide the overlay ***/
});
$('.overlay-bg').click(function(){
$('.overlay-bg').hide();
});
$('.overlay-bg').click(function(){
return false;
})
});
});
})
});
JSON Object Below
[{"id":"39","sounds_like":"Beyonce","sound_name":"Dance 4 u.mp3","sound_desc":"Smooth","sound_genre":"R&B","sound_price":"N/A","photo_path":"\/admin_data\/uploaded_artist_photos\/","photo_name":"beyonce.jpg"},
{"id":"40","sounds_like":"Drake","sound_name":"Bottom.mp3","sound_desc":"Wu Tang Forever","sound_genre":"Rap","sound_price":"N/A","photo_path":"\/admin_data\/uploaded_artist_photos\/","photo_name":"drake.jpg"},
{"id":"41","sounds_like":"Nicki Minaj","sound_name":"RomanReloaded.mp3","sound_desc":"Barbie","sound_genre":"Rap","sound_price":"N/A","photo_path":"\/admin_data\/uploaded_artist_photos\/","photo_name":"nickiminaj.jpg"}
]
When you loop a complex object using a for var in loop, you will always have unexpected behaviors because of how this loop works.
To avoid such problems and if you need to use this type of loop, I recommend you do the following:
Example:
for (var i in obj) {
if (obj.hasOwnProperty(i)) { // this validates if prop belongs to obj
// do something
}
}
EDIT 1:
I'm not sure what you're trying to do but using jquery you can do the following:
$.getJSON("php/music_data.php", function (data) {
$.each(data, function (i, value) {
//alert(i + ": " + value.id);
alert(value.sounds_like);
// this will have Beyonce , Drake, Nicki Minaj
});
});
Another thing that does not seem right is that you're doing bind click event on each loop. Is it better to do this differently.
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.
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);