I'm trying to generate a series of buttons from a loop. On each button click, it should display the file.path of each button. The id is assigned dynamically from the loop itself. It is only displaying for the first one. here is the code:
Onclickling the button, it display the path for doc 1. But when clicking the second button, it display the path for doc1 too. It should display the path of doc 2
var result = {"data":"{\"files\":[{\"name\":\"doc1.pdf\",\"title\":\"networking\",\"path\":\"mfpreader.comze.com\\\/files\\\/doc1.pdf\"},{\"name\":\"doc2.pdf\",\"title\":\"Armoogum\",\"path\":\"mfpreader.comze.com\\\/files\\\/doc2.pdf\"}]}","isSuccessful":true};
var str= '';
var files = JSON.parse(result.data).files;
for(var file, i = 0; i < files.length; i++) {
file = files[i];
str += file.name + '<br />' + file.title + '<br/>' + '<input type="hidden" id="b" value="'+ file.path +'" />' + '<button onclick="add()">Add</button> '+ '<br/>' ;
}
alert(str);
$("#viewlist").html(str);
function add() {
var b = document.getElementById('b').value;
alert(b);
}
I will really appreciate it if i can get some help. Thank you.
All of your buttons have the same id, that is not going to work. There are a couple of ways of doing this. I modified your HTML slightly to group each section so you can easily find the associated hidden field for the button. I also passed in a reference to the button being clicked to the add function:
var result = {"data":"{\"files\":[{\"name\":\"doc1.pdf\",\"title\":\"networking\",\"path\":\"mfpreader.comze.com\\\/files\\\/doc1.pdf\"},{\"name\":\"doc2.pdf\",\"title\":\"Armoogum\",\"path\":\"mfpreader.comze.com\\\/files\\\/doc2.pdf\"}]}","isSuccessful":true};
var str= '';
var files = JSON.parse(result.data).files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
str += file.name + '<br /><div class="fileSection">' + file.title + '<br/>' + '<input class="fileName" type="hidden" id="b" value="'+ file.path +'" />' + '<button onclick="add(this)">Add</button> '+ '</div><br/>' ;
$("#viewlist").html(str);
function add(btn) {
var b = $(btn).closest('.fileSection').find('.fileName').val();
alert(b)
}
Where is str defined? I suspect it might be inside the for loop, but you want to make sure that you define it before the loop:
var str = '';
for(var file, i = 0; i < files.length; i++) {
file = files[i];
str += file.name + '<br />' + file.title + '<br/>' + '<input type="hidden" id="b" value="'+ file.path +'" />' + '<button onclick="add()">Add</button> '+ '<br/>' ;
}
I think the output is then what you are looking for.
Related
I am setting a field in my HTML label from Viewbag which has a "'" in the text. when the HTML pulls up it shows ' in place of "'". How do I stop it from getting encoded?
Please find the code below.
setting text fileds in the HTML view.
$('#thStudentName').text('#ViewBag.Name');
if (sessionData.data.EventDate2Def != '' || sessionData.data.EventDate2Def != null)
$('#tdWhen').text(sessionData.data.EventDate1Def + ' and ' + sessionData.data.EventDate2Def);
else
$('#tdWhen').text(sessionData.data.EventDate1Def);
$('#tdWhere').text(sessionData.data.FacilityName);
$('#tdLocated').text(sessionData.data.Address1 + ', ' + sessionData.data.City + ', ' + sessionData.data.State + ' ' + sessionData.data.Zip);
$('#tdPhone').text(sessionData.data.Phone);
$('#tdDirections').text(sessionData.data.Directions);
$('#tdRoom').text(sessionData.data.RoomNumber);
Populating a different section with Dynamic data.
function populateSessionTable() {
var count = 1;
$('#SessionTable').html('');
var tableContent = '';
var record = '';
var Sessions = sessionData.data.Sessions;
tableContent = generateTableContent(count, Sessions[0].StartDateTimeDef);
tableContent += '</tbody></table></div>';
$('#SessionTable').html(tableContent);
var radioStatus = '';
for (var i = 0; i < Sessions.length; i++) {
var content = Sessions[i];
radioStatus = '';
if (content.Capacity == content.Registered || content.Closed)
radioStatus = '<input disabled class="selected-session radio" name="SessionId" type="radio" value="' + content.SessionId + '">';
else if (content.StartDateTimeDef == '#ViewBag.WorkshopDateDef' && t24to12Convert(content.StartTimeString) == t24to12Convert('#ViewBag.WorkshopTime'))
radioStatus = '<input class="selected-session radio" checked name="SessionId" type="radio" value="' + content.SessionId + '">';
else
radioStatus = '<input class="selected-session radio" name="SessionId" type="radio" value="' + content.SessionId + '">';
record += '<tr>';
record += '<td class="session-schedule-table-btn">';
record += radioStatus;
record += '</td>';
record += '<td class="session-schedule-table-session-number"> ' + content.Number + ' </td>';
record += '<td class="session-schedule-table-session-start-time">' + t24to12Convert(content.StartTimeString) + '</td>';
record += '</tr>';
$('#SessionTBody' + count).append(record);
record = '';
if(Sessions.length != i + 1)
{
if(Sessions[i].StartDateTimeDef != Sessions[i + 1].StartDateTimeDef)
{
tableContent = '';
count++;
tableContent = generateTableContent(count, Sessions[i+1].StartDateTimeDef);
tableContent += '</tbody></table></div>';
$('#SessionTable').append(tableContent);
}
}
}
}
populateSessionTable();
The preview shows the name in the correct format, but when it gets rendered instead of having the quote, it shows '
This is how the output is coming up
So finally it was a stupid problem and I swear I had tried this before, but this is the code that worked.
var stuName = '#ViewBag.Name';
stuName = stuName.replace("'", "'");
$('#thStudentName').text(stuName);
Here is my code, I wanna get the element info in the click function like my annotation says.
for(var i = 0, len = json.length; i < length; i++) {
var curid = json['success'][i]['courier_id'];
var curname = json['success'][i]['courier_name'];
document.getElementById("gsid").value=curname;
var tr="<tr> ";
//here is where i want to use onclick function with curid and curname
var td1="<td>"+"<input type='radio' name='as' value='json['success'][i]['courier_id']' id='curiid' onclick='courierselect(<?php echo $shyam='\'+curname+\''; ?>);'/>"+"</td> ";
var td2="<td id='curnname'>"+json['success'][i]['courier_name']+"</td> ";
var td3="<td>"+json['success'][i]['country_charge']+"</td> ";
var td4="<td>"+json['success'][i]['estimate_delivery_time']+"</td> ";
var td5="<td>"+json['success'][i]['tracking_available']+"</td></tr> ";
$("#results").append(tr+td1+td2+td3+td4+td5);
}
I see three problems on your code
... value='json['success'][i]['courier_id']' ...
You didn't concact the variable with the string
... courierselect(<?php echo $shyam='\'+curname+\''; ?>) ...
echo $shyam='\'+curname+\''; you can't set a PHP variable with a JS value. Understand why
You echo a string value, so you have to add some quotes around curname
for(var i = 0, len = json.length; i < length; i++) {
var curid = json['success'][i]['courier_id'];
var curname = json['success'][i]['courier_name'];
document.getElementById("gsid").value = curname;
$("#results").append('<tr> ');
$("#results").append('<td><input type="radio" name="as" value="' + curid + '" id="curiid" onclick="courierselect(\'' + curname + '\');"/></td> ');
$("#results").append('<td id="curnname">' + curname + '</td> ');
$("#results").append('<td>' + json['success'][i]['country_charge'] + '</td> ');
$("#results").append('<td>' + json['success'][i]['estimate_delivery_time'] + '</td> ');
$("#results").append('<td>' + json['success'][i]['tracking_available'] + '</td></tr> ');
}
I've tried multiple solutions but none worked and I don't understand why...
Basically, I have a button that appends a new form line into my page, with name, start and colour fields and a save button.
What I need to do is save the form fields on save click.
Here's the code I'm trying to use but it's not working:
var i = 0;
var addCounter = $("#addCounter");
addCounter.on("click", function () {
++i;
var body = $("body");
var save = $('#save-' + i);
var name = $("#counterName-" + i);
var date = $("#counterStart-" + i);
var color = $("#counterColor-" + i);
var status = $("#status-" + i);
var templateToAppend = '<li class="list-group-item">' +
'<div class="form-inline">' +
'<div class="form-group">' +
'<label for="counterName-' + i + '">Counter Name</label>' +
'<input type="text" id="counterName-' + i + '" placeholder="Counter name"/></div>' +
'<div class="form-group">' +
'<label for="counterStart-' + i + '">Starting from:</label>' +
'<input type="text" id="counterStart-' + i + '" placeholder="dd/mm/yy"/></div>' +
'<div class="form-group">' +
'<label for="counterColor-' + i + '">Counter Color:</label>' +
'<input id="counterColor-' + i + '" class="jscolor"></div>' +
'<button id="save-' + i + '" class="btn btn-primary">Save</button>' +
'<div id="status-' + i + '"></div></div></li>';
body.append(templateToAppend);
save.click(function () {
debugger;
console.log("clicked on save: ", save);
var localStorage = {
id: i,
counterName: name.value,
counterDate: date.value,
counterColor: color.value
};
console.log(localStorage);
});
});
the debugger never runs and I don't understand why.
Can you please help me understand why?
thanks a lot
Well that is because you have tried to create jquery object of element which is not there in DOM. You should append the element first and then get element by selector. Like this:
body.append(templateToAppend);
var save = $('#save-' + i);
var name = $("#counterName-" + i);
var date = $("#counterStart-" + i);
var color = $("#counterColor-" + i);
var status = $("#status-" + i);
also there is much cleaner way to attach event to dynamically added element. Have a look at Event Delegation
var save = $('#save-' + i);
This line of code is executing before the button is added to the document.
save will be an empty array.
Use event delegation for you second click event,place the click event outside the first click event
$('body').on('click','.list-group-item btn',function () {
console.log("clicked on save: ", $(this).attr('id'));
var i = $(this).attr('id').split('-')[1];
var localStorage = {
id: i,
counterName: $("#counterName-" + i).val(),
counterDate: $("#counterStart-" + i).val(),
counterColor: $("#counterColor-" + i).val()
};
console.log(localStorage);
});
I have form and it look like this:
<div class="fieldWrapper">
<label for="id_rooms">Rooms:</label>
<input id="id_rooms" type="number" name="rooms" min="1">
</div>
<div class="extrafieldWrapper">
</div>
And I have script that add or delete couple of fields 'adult' and 'children' depending on value of field 'room'. Now i want to do the same thing with field 'children': depending on value of field 'children' script should add or delete fields 'children_age'. I tried to realize it something like this, but it isn't work.
$(function () {
$('#id_rooms').bind('blur keyup change', function () {
var n = $('#id_rooms').val() || 0;
$("input[id='id_form-TOTAL_FORMS']").attr('value', n);
$(".extrafieldWrapper").empty();
for (var i = 0; i < n; i++) {
$(".extrafieldWrapper").append("<br/><label for='id_form-" + i + "-adult'>Adult:</label> <input id='id_form-" + i + "-adult' type='number' name='form-" + i + "-adult'/> <label for='id_form-" + i + "-children'>Children:</label> <input id='id_form-" + i + "-children' type='number' name='form-" + i + "-children'/><div id='extrafieldWrapperChAge'></div>");
$("#id_form" + i + "children").bind('blur keyup change', function() {
var n = $("#id_form" + i + "children").val() || 0;
$(".extrafieldWrapperChAge").empty();
for (var i = 0; i < n; i++) {
$(".extrafieldWrapperChAge").append("<br/><label for='id_form-" + i + "-childrenage'></label><input id='id_form-" + i + "-childrenage' type='number' name='form-" + i + "childrenage' />");
}
});
}
});
});
I am newbie in java-script, can you tell me what i'm doing wrong. Thanks a lot.
Extract your inner code and use only one event handler for the childrens age field(s). In the code below I have added the class children_age to the input fields and then attached a event handler to listening for changes on all elements with that class.
Note 1: It should be enough to listen for change events.
Note 2: Use on instead of bind since it's recommended by the jQuery team
$(function(){
$('#id_rooms').on('change', function(e){
var n = $('#id_rooms').val() || 0;
var html = "";
for (var i = 0; i < n; i++) {
html += "<br/><label for='id_form-" + i + "-adult'>Adult:</label>"
+ "<input id='id_form-" + i + "-adult' type='number' name='form-" + i + "-adult'/>"
+ "<label for='id_form-" + i + "-children'>Children:</label>"
+ "<input id='id_form-" + i + "-children' type='number' name='form-" + i + "-children' class='children_age'/>"
+ "<div class='extrafieldWrapperChAge'></div>";
}
$(".extrafieldWrapper").html(html);
});
$(".extrafieldWrapper").on('change', '.children_age', function(e){
// $(this) refers to the element that changed
var n = $(this).val() || 0;
var html = "";
for (var i = 0; i < n; i++) {
html += "<br/><label for='id_form-" + i + "-childrenage'>Age of child "+(i+1)+"</label>"
+ "<input id='id_form-" + i + "-childrenage' type='number' name='form-" + i + "childrenage' />";
}
//.next - finds the next occurrence that matches the selector
$(this).next('.extrafieldWrapperChAge').html(html);
});
});
I have a webpage that based on user input populates with form fields, as done by the following:
function Go2() {
var loans = document.getElementById('count').value;
var content = document.getElementById('stage3').innerHTML;
content = '<TABLE Width="100%">'
+'<TR>'
+'<TD Style="font-weight:bold;" Width="30%">Customer Name</TD>'
+'<TD Style="font-weight:bold;" Width="30%">Customer Number</TD>'
+'<TD Style="font-weight:bold;" Width="30%">Origination Date</TD>'
+'</TR>'
+'</TABLE>';
document.getElementById('stage3').innerHTML = content;
for(var i=0; i<loans; i++) {
content = document.getElementById('stage3').innerHTML;
document.getElementById('stage3').innerHTML = content
+ '<TABLE Width="100%">'
+ '<TR>'
+ '<TD Width="30%"><INPUT Name="CName'
+ i
+ '" Size="40" Type="text"></TD>'
+ '<TD Width="30%"><INPUT Name="CNumber'
+ i
+ '" Size="40" Type="text"></TD>'
+ '<TD Width="30%"><INPUT Name="Date'
+ i
+ '" Size="40" Type="text"></TD>'
+ '</TR>'
+ '</TABLE>';
}
content = document.getElementById('stage3').innerHTML;
document.getElementById('stage3').innerHTML = content
+ '<TABLE><TR><TD><INPUT Type="Button" Value="Submit" onClick="Go3()"></TD></TR></TABLE>';
}
Now what I need to do is iterate through the form and pull out the values for each of the form fields. This is about as far as I've gotten:
for (var n=0; n<loans; n++) {
content += '<TR>'
+ '<TD Colspan="2">'
+ document.getElementById('CName + n').value
+ '</TD>'
+ '<TD Colspan="2">'
+ document.getElementById('CNumber + n').value
+ '</TD>'
+ '<TD>'
+ document.getElementById('Date + n').value
+ '</TD>'
+ '</TR>';
}
Which does...Nothing. The last notable progress I had was getting it to spit out "null" which isn't really progress at all. I've looked at eval, but there's quite a few warnings against it.
Any Ideas?
I think you want
document.getElementById('CName' + n).value
(where n is outside of the quotes)
Well it should be 'CName' + n - i.e., you got the quotation marks in the wrong place
If all your controls are in a form, then you can access them as:
var allControls = document.<formId>.elements;
or
var allControls = document.forms[formId].elements;
Then iterate over the list of controls to get the values. The form controls must have names to be successful, no need for IDs. You can also get the values as:
var value = allControls['CName' + n].value;
or just
var form = docment.forms[formID];
var value = form['CName' + n].value;