Jquery reading input field that was created from JSON loop - javascript

I cannot figure out for the life of me why this will not work. I am trying to pull the value of a textfield that was created with a loop from a json file.
In this code, at the very bottom I just do a simple click(function() {alert()} just to see if I can pull a value and its returning undefined. But if I remove '#name' and put in 'input' it captures it, but only for the first of several input fields.
Any help is really appreciated
JSON
{
"Controls": [{
"Button":[{ "Name":"Button", "x": "1","y": "2","width": "3","height": "4","Transition":"" }],
"Image":[{"x": "5","y": "6","width": "7","height": "8"}],
"TextField":[{"x": "9","y": "10","width": "11","height": "12","Rows":""}]
}]
}
The Code(there is soome getJSON stuff above this)
//Slide In Attributes Panel Based on Selected Object
$(document).on('click', '#code li', function () {
var index = $('#code li').index(this);
var selected = $(this).text();
switch (selected) {
case selected:
$('#options').hide();
hidePanels();
$('#temp').remove();
$('#objectAttributes').show("slide", 200);
break;
//If it does work show what variable is being used
default:
alert(selected);
break;
}
//Shows Selected LI Index
$('#codeIndex').text("That was div index #" + index);
//Pull list of Attributes for selected Object
$.getJSON('controls.json', function (data) {
//Build Attributes List
var attributeList = '<div id="temp">';
//Target based on selected object
var target = selected;
attributeList += '<div>' + target + '<div>';
$.each(data.Controls[0][target][0], function (kk, vv) {
attributeList += '<div style="float:right">' + kk + ':' + '<input type="text" id='+ kk + '>' + '</input>' + '</div>';
});
attributeList += '</div></div>';
attributeList += '</div>';
$('#objectAttributes').append(attributeList);
$('#temp').append('<div id="editIndex">'+"Modifying index" + " " +index+'</div>');
$(document).on('click', '#saveAttributes', function () {
var $x = $('#name').val();
alert($x);
})
});
});

Ok, so after a little hacking around with a jsfiddle the answer turned out to be a lot simpler than I first thought. Ever since HTML 4.01 class names and IDs have been case sensitive (reference), which means that your selector $('#name') wasn't matching the JSON Name.
So a simple change, such as in this simplified jsfiddle seems to work as desired. Hopefully this helps!

Related

how do i capture which number <div> got clicked on inside my container <div> and store it in a variable

edit: my code is all held inside a $(document).ready(function() {} because of this, and because my html code is generated inside my javascript file on the fly, i am experiencing issues using .click() when applying the answer that was given to use
$('.movies_cell').click(function(){
var tmp = $(this).index();
});
original:
i have 20 div elements on a page with a class of .movies_cell that are all generated from an ajax file. All of the div's are created within container div called #movies.
any of the .movies_cell div's can be clicked to bring up a modal box, because i am going to place information from my json file in that modal depending on what gets clicked i need to know which div got clicked, for instance, if it was the 5th div i want to know that the 5th div was clicked and then store that number in a variable, if it was the 2nd, or 3rd i want that number to be stored in a variable and then clear when another .movies_cell div gets clicked.
how would i write a javascript or jquery script to accomplish this? :(
thanks!
$('#myMovies').click(function () {
$.getJSON('data/movies.json', function (allData) {
$.each(allData, function (i, field) {
$('#movies').append(function () {
var movies = '<div class="movies_cell">';
movies += '<div class="movies_image">';
movies += '<img src="img/movies/' + (field.image) + '" alt="' + (field.name) + ' Poster" style="width: 100%; height: 100%">';
movies += '</div>';
movies += '<div class="movies_detail">';
movies += '<h1>' + (field.name) + '</h1>';
movies += '<img src="img/rating/' + (field.myRating) + '.png" alt="movie rating" style="margin: auto;">';
movies += '</div>';
movies += '</div>';
counter++;
console.log(counter);
return movies;
});
});
});
});
Use event delegation.(https://api.jquery.com/on#direct-and-delegated-events) At the top
$('#movies').on( "click", ".movies_cell > div", function() {
var tmp = $(".movies_cell > div").index(this);
console.log(tmp);
});
then
$('#myMovies').click(function () {
//rest of code
Can you use .index() ? It is a zero-based index of the collection of items with, for example, class="movies_cell"
$('.movies_cell').click(function(){
var tmp = $(this).index();
});
jsFiddle Demo

Is it possible to bind events during element concatenation in a loop?

Fiddle Example
The following is an example where several buttons are rendered via a loop. I was wondering if it is possible to bind events to each button as well during the loop before the buttons are appended to a container. My example doesn't work.
Jquery
function render(){
var input = '',
array = [{'name':'Confirm','title':'This'},{'name':'Cancel','title':'That'}]
$.each(array,function(k,obj){
var name = obj.name;
input += '<h3>'+obj.title+'</h3>';
input += '<input type="submit" name="'+name+'" value="'+name+'"/>';
$(input).find('[name="'+name+'"]').click(function(){
alert(name)
/*** do some ajax things etc ***/
})
})
return input;
}
$('#box').append(render())
Yes but I wouldn't do it the way you are:
function render(target){
var array = [{'name':'Confirm','title':'This'},{'name':'Cancel','title':'That'}]
$.each(array,function(k,obj){
var name = obj.name;
var h3 = $('<h3/>').text(obj.title);
var input = $('<input/>')
.attr('type', 'submit')
.attr('name',name)
.val(name);
input.click(function() {alert('test');});
target.append(h3);
target.append(input);
})
}
$(document).ready(function(){
render($('#box'));
});
So create jquery objects that will be rendered, then attach the event to these objects. Then once the object is built ask jquery to render them.
This way jquery can keep track of the DOM elements, in your example your stringfying everything. Jquery hasn't built the DOM element at the point where your attempting to bind to them.
Fiddle
You need to use filter() to find the element by the name as there is no parent selector to find() within:
$(input).filter('[name="' + name + '"]').click(function(){
alert(this.name)
/*** do some ajax things etc ***/
})
No, you can't bind event handlers to strings. You will need to create HTML elements first. I would recommend to bind single delegated event handler after your HTML string is appended, it's also going to be much better in terms of performance:
function render() {
var input = '',
array = [{'name': 'Confirm','title': 'This'}, {'name': 'Cancel','title': 'That'}]
$.each(array, function (k, obj) {
var name = obj.name;
input += '<h3>' + obj.title + '</h3>';
input += '<input type="submit" name="' + name + '" value="' + name + '"/>';
});
return input;
}
$('#box').append(render()).on('click', 'input[name]', function() {
alert(this.name);
/** do some ajax things etc **/
});
Demo: http://jsfiddle.net/KHeZY/200/
This can be done properly by using event-delegation, But since you concerned, I just written a solution by using .add() and .filter()
function render() {
var input = '',
array = [{
'name': 'Confirm',
'title': 'This'
}, {
'name': 'Cancel',
'title': 'That'
}],
elem = $();
$.each(array, function (k, obj) {
var name = obj.name;
input += '<h3>' + obj.title + '</h3>';
input += '<input type="submit" name="' + name + '" value="' + name + '"/>';
elem = elem.add($(input));
input = "";
});
elem.filter("[name]").click(function () {
alert(this.name);
})
return elem;
}
$('#box').append(render())
DEMO

How to style dynamically generated Select2 dropdowns after the page has loaded?

I am using Select2 for dropdown styling from http://ivaynberg.github.io/select2/ .
I have several dropdowns on the page which are styled correctly using the following:
<script>
$(document).ready(function() {
$("#dropdown1").select2();
$("#dropdown2").select2();
});
</script>
Now, I have another option on the page where it allows the user to add as many dropdowns as they want for additional options, the following way:
<img src="images/add.png" title="Add Row" border="0" onclick="addRowToCountryPrice('',''); return false;">
<input type="hidden" name="TotalLinesCountry" id="TotalLinesCountry">
<script>
var arr = new Array();
var ind=0;
function showCountryDrop(name1,sel, param){
var dval="";
dval = "<select name=\"" + name1 + "\" id=\"" + name1 + "\" class=\"countriesclass\">";
dval += "<option value=\"\">Select Country</option>\r\n";
selVal = (sel==0001) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0001\" " + selVal + ">United Kingdom</option>";
selVal = (sel==0002) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0002\" " + selVal + ">United States</option>";
selVal = (sel==0003) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0003\" " + selVal + ">Albania</option>";
selVal = (sel==0004) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0004\" " + selVal + ">Algeria</option>";
dval +="</select>";
return dval;
}
function addRowToCountryPrice(country,price) {
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
var cellVal = "";
var cellLeft;
var i=0;
arr[ind] = (iteration+1);
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = showCountryDrop("countryDrop_" + ind,country);
cellLeft = row.insertCell(i++);
var price = (price!=0) ? price : "0.00";
cellLeft.innerHTML = "<input type=\"text\" name=\"countryPrice_" + ind + "\" id=\"countryPrice_" + iteration + "\" value = \"" + price + "\" size=\"8\">";
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = "<img src=\"images/delete.png\" title=\"Delete Row\" border=\"0\" onclick=\" removeRowFromTable(" + ind + "); return false;\">";
document.getElementById("TotalLinesCountry").value = (parseInt(ind)+1);
ind++;
}
function removeRowFromTable(src)
{
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
if (arr[src]!="") tbl.deleteRow((arr[src]-1));
arr[src]="";
var counter = 1;
for( i=0; i<arr.length; i++) {
if (arr[i]!="") {
arr[i]= counter;
counter++;
}
}
return false;
}
</script>
While it generates the dropdowns correctly, they are not styled through the class "countriesclass", even if I do a:
$(".countriesclass").select2();
I also tried
dval +="</select>";
$(".countriesclass").select2();
return dval;
And that seems to be PARTIALLY working in a strange way. When I create the first dropdown, it doesn't get styled. When I create another second dropdown, then the first one gets styled but the second one doesn't. It then doesn't let me create further ones and shows an error.
Any ideas how I could get this working?
UPDATE: jsFiddle http://jsfiddle.net/y6af098z/2/
Your call to $('.countriesclass') goes off when the document is ready. But the select has not been added to the document yet, then. So no elements are found.
You should look up the added select after the user has clicked on the plus and you've added the select to the dom.
$('#plus').on('click', function () {
$tr = addRowToCountryPrice('Algeria', 0);
$('.countriesclass', $tr).select2();
});
The second argument $tr tells jquery only to look in the recently added table row, so that you only select the newly added select which is a child of the newly added tr. Not the selects in the other rows.
Like #dreamweiver already noted, you should make better use of jquery when creating the dom elements. That's what jquery is good at. I've updated the jsfiddle to show how you can create the select and table row the jquery way.
DEMO
Instead of using getelementbyId use getelementbyClass and give each dropdown a class, you can only have one getelementbyid.
Hope this helps. if you want i could send you the code for what you require?
The select2 when called was not able to find the dropdown list boxes,because they were added dynamically and hence the those were not visible for the jQuery class selector $(".countriesclass").select2();.
This type of behaviour can be overcome by referencing the selector from the document element, rather than referring the element directly like above. so the new selector should be like this
$(document).find("select.countriesclass").select2();
Also I have done few tunings in your code.
Live demo:
http://jsfiddle.net/dreamweiver/y6af098z/8/
Note: one more thing, when using jQuery lib make sure you make the most of it, don't use raw JS code instead use the jQuery equivalent syntax for the same, which would be simple and easy to use.

how to refresh the list in jquery javascript

Hi i m having one page with one textbox named search and one search button. When i'm searching anything for the first time it's showing me the right data but when i'm searching some other things for the next time then the elements which was listed before are also appended below of that new list. Suppose i'm searching state name by k it will give me right list of karnataka, kerala. But if i start to search again by g, it will show me in output as goa,gujrat,karnataka kerala. i tried using refresh option but it still not working. This is my js code
$.each(response.state, function (i, state) {
$('#statelist').append(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});
$("#statelist").listview("refresh");
and this is html
You are using .append() function. It appends whatever you append to the end of the list.
Check this link:
http://api.jquery.com/append/
Try using innerHTML property of the DOM model.
You could add
If(!('#statelist').html() == ""){
$(this).remove();
//execute rest of code that appends state list
}
Then do an else statement and execute your append code without removing()
UPDATE: a better option is to do this-
$.each(response.state, function (i, state) {
$('#statelist').html(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});

Trying to connect a dynamically created select element (tag) with options to a dynamically created table row

The first block of code is a working example of what I want the variable select to do. the var Select is there to be a td in the variable tr. the variable tr is used 2 times in this code. once to to append the tr when the table has html and another time when it doesn't have any html. the reason is because if doesn't have html it should append the header and the row with the select element and the rest of the data that's supposed to be on the row and if does have html it should only append the row to prevent repetition of the header. so I would like a nice clean variable named tr that will be append every time the users invokes it. jsfidle if you click on the drop down you could select the item and the new row will appear.
$('#autocomplete').autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
var thehtml = '<strong>Item:</strong> ' + suggestion.value + ' <br> <strong>price:</strong> ' + suggestion.data + "<br>" + suggestion.divs;
var tableheader = ($("<thead>")
.append($("<tr>")
.append($("<th>Item</th><th>Qty</th><th>Price</th>")))
)
var select = " <select class = 'select'><option value='volvo>Volvo</option> <option value='saab'>Saab</option> <option value='mercedes'>Mercedes</option> <option value='audi'>Audi</option> </select>"
var tr = "<tr><td>"+ suggestion.value + "</td><td>" +select +"</td></tr>"
if($(".table").html().length <= 0)
{
$('.table').append($("<table>")).append(tableheader).append(tr);
}else{
if($(".table").html().length > 0){
$(".table").append(tr)
}
}
The thing is I want the select element to be made up dynamically so i tried something and I cant figure out why it wont work. It's not recieving the variable. Am i implementing the varable wrong with the $.each?
$('#autocomplete').autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
var thehtml = '<strong>Item:</strong> ' + suggestion.value + ' <br> <strong>price:</strong> ' + suggestion.data + "<br>" + suggestion.divs;
var tableheader = ($("<thead>")
.append($("<tr>")
.append($("<th>Item</th><th>Qty</th><th>Price</th>")))
)
var selectValues = { "3": "2", "2": "1" , "1": "..."};
var select = $.each(selectValues, function(key, value){
$('.select').append($('<option>', {value: value}).text(value));
// <option value='volvo>Volvo</option>
});
var tr = "<tr><td>"+ suggestion.value + "</td><td><select class ='select'>" + select + "</select></td></tr>";
if($(".table").html().length <= 0)
{
$('.table').append($("<table>")).append(tableheader).append(tr);
}else{
if($(".table").html().length > 0){
$(".table").append(tr)
}
}
},
maxHeight:100,
width:600
});
thanks for your help
Why use object if you use only value?
if you realy don't need key juste create an array :
var selectValues = ["2", "1", "..."];
var value;
var select = selectValues.forEach(function(value){
$('.select').append($('<option>', {value: value}).text(value));
// <option value='volvo>Volvo</option>
});
// or if you want more compatibility
for (var i = 0, len = selectValue.length; i < len; i++) {
value = selectValue[i];
$('.select').append($('<option>', {value: value}).text(value));
});
Edit:
i make some mistake sorry.
first forEach will return nothing so it's can't work.
I test with your fidle. try this (replace by old for loop if you don't want to use map).
var select = selectValues.map(function(value){
return "<option value=" + value + ">" + value + "</option>";
// <option value='volvo>Volvo</option>
}).join('');
first you do not have to append from $('.select') because this dom not exist at this moment
and you can't concate an array in a string like this.

Categories

Resources