I am creating a div dynamically with ajax. Now if the ajax call is success then i created a string for div element and append it to the original div id.
here is my code
$.ajax({
type:"GET",
url:"resources/json/asnData.json",
dataType:"json",
success:function(data){
$.each(data.Payload, function(index, val){
i=i+1;
stmt+='<div class="row">'+
'<section class="col col-2">'+
'<label class="input"><i class="icon-append fa fa-key"></i>'+
'<input type="text" name="keyName" value="'+val.key+'" readonly/>'+
'</label>'+
'</section>'+
'<section class="col col-3">'+
'<label class="select">'+
'<select id="dataConversionType'+i+'" class="dataConversionType">'+
'<option value="HEX">HEX</option>'+
'<option value="ALL">Compare All</option>'+
'<option value="ASCII">ASCII</option>'+
'<option value="STRING">STRING</option>'+
'<option value="INT">INTEGER</option>'+
'<option value="BINT">BIG INTEGER</option>'+
'</select><i></i>'+
'</label>'+
'</section>'+
'<section class="col col-5">'+
'<label class="input"><i class="icon-append fa fa-dashcube "></i>'+
'<input id="convertedType'+i+'" type="text" value="'+val.value+'" readonly/>'+
'</label>'+
'</section>'+
'</div>';
});
$(".dataParser").append(stmt);
Now there is function where if someone select a value in selectbox then fire and show.
$('#dataConversionType'+i).change(function(e) {
e.preventDefault();
var conversionType=$(this).val(); //I have doubt here also..
console.log(conversionType);
if(conversionType == 'ALL') {
console.log('ALL-Show a modal with each possible conversion');
}
but this is not working. this function works if I called using the class name. But i have to call the function using id with the i value, so that with that i value i can also set some value in other fields.
any help will be appreciated...
Use class instead of id (replace document with some non dynamic container)
$(document).on('change','.dataConversionType',function(e) {
e.preventDefault();
var conversionType=$(this).val();
console.log(conversionType);
var index_val = $(this).attr('data-index')
if(conversionType == 'ALL') {
console.log('ALL-Show a modal with each possible conversion');
}
)};
And when you are generating your element add a data attribute
'<select id="dataConversionType'+i+'" class="dataConversionType" data-index="'+i+'">'
Also if you are inside a loop you need to wrap your ajax within a closure if you want to get correct value and not the latest one.
(function(idx) {
//ajax stuff here
}(i)
Do one thing, Listen to the change event using class name itself, instead of Id.
Put value of i as a custom attribute into the select box. In the listener function, read this attribute and call or perform whatever actions you have to do.
A sample is as below:
'<section class="col col-3">'+
'<label class="select">'+
'<select id="dataConversionType'+i+'" class="dataConversionType" data-count=i>'+
'<option value="HEX">HEX</option>'+
'<option value="ALL">Compare All</option>'+
'<option value="ASCII">ASCII</option>'+
'<option value="STRING">STRING</option>'+
'<option value="INT">INTEGER</option>'+
'<option value="BINT">BIG INTEGER</option>'+
'</select><i></i>'+
'</label>'+
'</section>'
Event listener:-
$('.dataConversionType').change(function(e) {
e.preventDefault();
var conversionType=$(this).val(); //selected value
var valueofI = $(this).attr("data-count");// Value of i
}
data-count is the custom attribute.
Try On change method
$(document).on('change','.dataConversionType',function(e) {
// Paste Your Code
});
OR
$(document).on('change','#dataConversionType',function(e) {
// Paste Your Code
});
$('#dataConversionType1').change(function(e) {alert("Changed")});
this code will not work for dynamically append select box.
you should try-
$(document).on("change","#dataConversionType1",function(){
alert($('#dataConversionType1 option:selected').val());
});
This works for me.
The value of i has been now changed to the latest one and this would not give you all the selectboxes anyways.
If you want to be specific about any select box, do it like:
$('#dataConversionType1').change(function(e) {
// code here
});
If you want to do something on all the selectboxes you have created, you can do it like:
$('[id^="dataConversionType"]').change(function (e) {
// Find the index: Count of i
var elmIndex = $(this).attr("id").replace("dataConversionType", "");
// Reflects the value of it in related input field
$("#convertedType3" + elmIndex).val($(this).val());
});
If you want to use the value of i later for operations, you can do it in 2 ways:
set the value of i in some data- attribute like: data-index=i (example below):
'<select id="dataConversionType'+i+'" class="dataConversionType" data-index="' + i + '">'+
Get the index from the id itself doing split or regex (example: /\d/).
Related
This is my fiddle : DEMO
I am adding the template ID read-only fields, based on selection of option. 1 for SMS, 2 for email etc..
Since there is a provision to add new category, how to dynamically add template IDs to newly added options?
//Adding Template ID based on option
$('#categoryevent').on('click', function() {
$('.actionConfig').empty();
var z = $("#categoryevent option:selected").text();
if (z == 'sms') {
var smsConfig = '<div class=form-group><label class="col-sm-2 control-label"for=templateId>Template ID: </label><div class=col-sm-8><input class=form-control id=templateId name=templateId value="1" readonly="readonly"></div></div>';
$('.actionConfig').append(smsConfig);
}
});
Instead of checking for the textual representation of the option, you should check for the value attribute. Since you did not add the value attributes yet for the options you hardcoded, you will have to do this as well, i.e. change:
<option>SMS</option>
to
<option value="0">SMS</option>
Alternatively, if you don't want to use the standard value attribute (e.g. because you want to avoid default beheviour) you can instead go for <option data-selectionId="1">SMS</option>. Obviously increment the id for each option you have in your select.
Now if you create a new option, you will have to set this data:
var val = $("#new-option-event").val().trim();
var opt = '<option value="'+ globalCounterVariable +'">' + val + '</option>';
globalCounterVariable += 1;
$('#categoryevent').append(opt);
$('#categoryevent').val(val);
$('#new-option-event').val('');
You will have to define a global veriable (actually outside of the scope of the .addevent handler is enough) that you initially will have to set to 3 (the number of hardcoded options).
Now you can do this:
$('#categoryevent').on('change', function() {
var selection = $(this).val(); //this is reference to the changed element, i.e. the select with Id 'categoryeveny'.
var html = '<div class="form-group"><label class="col-sm-2 control-label" for="templateId">Template ID: </label><div class="col-sm-8"><input class="form-control" id="templateId" name="templateId" readonly="readonly"></div></div>';
$(html).find("input").val(selection);
$(".actionConfig").empty();
$('.actionConfig').append(html);
});
Note how I removed the need for all the if clauses, because you did the same logic each branch. Simply parameterize whatever you want to inject and this is all you need.
If you want to show different values for each selection (so different data than 1,2,3,... etc), you will have to either make that an option in the input where you create a new option, or hardcode generic logic in the change event, where you decide what content is shown based on the value of selection.
Welcome to SO,
you can do something like this,
Set value of option as Template-Id 1,2,3 now when you add new category maintain counter and add it as value of newly added option.
Now keep other things same just get template id from option value.
something like this,
var opval = get option value here..
var smsConfig = '<div class=form-group><label class="col-sm-2 control-label"for=templateId>Template ID: </label><div class=col-sm-8><input class=form-control id=templateId name=templateId value="+opval+" readonly="readonly"></div></div>';
$('.actionConfig').append(smsConfig);
Hope this helps.
Edit:
answer jsfiddle
Here is the answer fiddle : DEMOanswer
$('#categoryevent').on("click", function(ev) {
// alert(ev.target.selectedIndex);
var value = ev.target.selectedIndex;
$('.actionConfig').empty();
var z = $("#categoryevent option:selected").text();
z = z.toLowerCase();
var templateId = '<div class=form-group><label class="col-sm-2 control-label"for=templateId>Template ID: </label><div class=col-sm-8><input class=form-control id=templateId value="' + value + '" name=templateId readonly="readonly"></div></div>';
$('.actionConfig').append(templateId);
});
I have a list of students that I am looping through and adding to my page. Each student has a unique ID, and when getStudentInfo is invoked, it does something with the id. The problem is that whichever student I click, I get back the same id, belonging to student1.
Where am I going wrong?
foreach ($students as $student) {
echo '<tr>';
echo '<td>
'.$student[student_permalink].'
<input type="submit"
value="info"
onclick="getStudentInfo()"
class="student-name-btn"
id="'.$student[student_permalink].'"
/>
</td>';
}
js:
function getStudentInfo() {
var studentLink = $('.student-name-btn').attr('id');
console.log(studentLink);
}
Your code is selecting all the buttons on the page with that class and than reads the id of the first one in the list. You are not limiting it to the one that was clicked.
What most people would do is add events with jQuery and not inline.
//needs to be loaded after the element or document ready
$(".student-name-btn").on("click", function() {
console.log(this.id);
});
For yours to work, you would need to pass a reference to the button that was clicked.
onclick="getStudentInfo(this)"
and than change it to use the node passed in
function getStudentInfo(btn) {
var studentLink = $(btn).attr('id');
console.log(studentLink);
}
You can pass the reference to the element being clicked on the onclick event
foreach ($students as $student) {
echo '<tr>';
echo '<td>
'.$student[student_permalink].'
<input type="submit"
value="info"
onclick="getStudentInfo(this)" // << added this which refers to the input
class="student-name-btn"
id="'.$student[student_permalink].'"
/>
</td>';
}
And then use that to fetch the id in the js
function getStudentInfo(el) {
var studentLink = $(el).attr('id');
console.log(studentLink);
}
Don't use inline events - there's no need to clutter up the HTML with that. You have a common class on your element, so just make a jQuery handler and use an instance of this
$('.student-name-btn').click(function() {
var id = this.id;
});
Like #epascarello alluded to, you are not selecting the button that was actually clicked. What you should do is have your event handling in your JS, not in the HTML so you can see better how it works and use the this keyword within the closure to reference the clicked button.
$(document).on('click', '.student-name-btn', function(evt) {
// Prevent default if trying to do your own logic
evt.preventDefault();
// Need to use the "this" keyword to reference the clicked element
var studentId = $(this).attr('id');
console.log(studentId);
});
You can do this without inline JavaScript and since you're using jQuery drop the onClick() and the form element:
echo '<tr>';
echo '<td id="'.$student['student_permalink'].'" >
'.$student['student_permalink'].'
</td>';
You also need to quote the identifier in the array variable, 'student_permalink'.
The jQuery will be this:
$('td').click(function() {
var studentLink = this.id;
console.log(studentLink);
});
I am working on code where user selects an item from dropdown list and the UI elements are displayed according to that selected item. Example: if item1 is selected there will be 2 textboxes, 1 textarea and a checkbox. item2 will have 1 textbox. etc.
So, I currently have a function where I add html elements according to item selected. I get a JSON file where there is list of items and what UI elements are required for that item. When user selects an item I get the required information from that JSON file and call following code:
$scope.myHTML = "";
var aForm = (angular.element(document.getElementById('appType')));
aForm.html('');
dropdown.forEach(function(viewItem, index){
if(viewItem.control_type === "TextBox"){
$scope.myHTML += '<label class="label">'+ viewItem.label +'</label>'+
'<input type="text" ng-model = "item.value'+index + '" placeholder = "'+ viewItem.text +'">';
}
if(viewItem.control_type === "TextArea"){
$scope.myHTML += '<label class="label">'+ viewItem.label +'</label>'+
'<textarea type="text" rows="4" ng-model = "tests.value'+index + '" ></textarea>'';
}
}
aForm.append($scope.myHTML);
$compile(aForm)($scope);
So the ng-model will have item.value0,item.value1 and so on for each element. I have used $compile to add the html view to UI.
The problem is that I can get the values in my controller but I cannot set those values from controller.
dropdown.forEach(function(viewItem, index){
$scope.tests['value'+index] = "SomePresetValue"; //Does not update value on HTML
});
Does not set value to the HTML element. I tried the following after searching for alternate solutions but did not work.
$scope.$apply(function(){
dropdown.forEach(function(viewItem, index){
$scope.item['value'+index] = viewItem.value;
});
});
I'm working with Zend Framework 1.12 and I've need to be able to dynamically add and delete fields from a sub-form, in this case we're associating hyperlinks to a parent "promotion".
I haven't found a way to accomplish dynamically adding and removing elements via Zend, and the rare tutorial I've found that claimed to do this are half a decade old and aren't working when I attempt them.
So what I am doing is storing the links I need to work with in a Zend Hidden input field and then dealing with the JSON data after I submit. Not very efficient, but it's the only thing I've gotten to work so far.
Below is the section of the code I'm working with:
Assume a form like:
<form action="/promos/edit/promo_id/15" method="POST" id="form_edit">
<!-- input is Zend_Form_Element_Hidden -->
<input type="hidden" id="link_array" value="{ contains the JSON string }"/>
<button id="add_link">Add Link</button>
</form>
The purpose is that every time the Add Link button is pressed, the form adds fields to allow the user to input new hyperlinks that will be associated with the specific items.
Here's the function:
// add links
$('#add_link').click(
function(e) {
e.preventDefault();
link = '<div class="p_link new_link">' +
'<div class="element_wrap">' +
'<label for="link_name" class="form_label optional">Text: </label>' +
'<input type="text" id="new_link_name" name="link_name"/>' +
'</div>' +
'<div class="element_wrap">' +
'<label for="link_http" class="form_label optional">http://</label>' +
'<input type="text" id="new_link_http" name="link_http"/>' +
'</div>' +
'<div class="element_wrap">' +
'<button class="submit delete_link">Delete</button>' +
'</div>' +
'</div>';
$('#add_link').prev().after(link);
}
);
Now, what I need to do is on submit, for every new_link class element, to take the links name and http reference and place it in a json object. Here's the code as I have it so far (I know I don't have both input fields represented at this point):
$('#submit').click(
function(e) {
e.preventDefault();
var link_array = [];
var new_links = document.getElementsByClassName('new_link');
$.each(new_links, function() {
console.log(this);
var n = $(this).children('#new_link_name').text();
console.log(n);
link_array.push({'link_name':n}); //'link_http':h
});
console.log(JSON.stringify(link_array));
}
);
My problem is that: var new_links = document.getElementsByClassName('new_link'); will collect all the newly added new_link elements, but it does not pull in any value that has been input into the text fields.
I need to know how I can apparently bind any input I make to the input field's value attribute, because right now anything I type into these new elements are tossed out and the field appears empty when it's anything but.
$('#submit').click(
function(e) {
e.preventDefault();
var link_array = [];
var new_links = $('.new_link');
$.each(new_links, function() {
console.log(this);
var n = $(this).find('input').val(); // you need input values! This line //is changed...
console.log(n);
link_array.push({'link_name':n}); //'link_http':h
});
console.log(JSON.stringify(link_array));
}
);
JSFIDDLE: http://jsfiddle.net/DZuLJ/
EDit: You can't have multiple IDS (make class for each input, and target class, if you want link names and http's)
I know this question was asked several times, but couldn't get the answer that works for me so here I am with my case.
I'm trying to make a jQuery plug-in that's add contact form to a certain page(It's not like there is no such a plug-ins but let's say I do this just for educational reasons). It is searching for <div id="add_contacts"></div> and creates the form in this div.
jQuery
$(document).ready(function(){
$('#add_contacts').append('<div class="contact-from"></div>');
$('<form></form>',{id:'new_contact'}).appendTo('.contact-form');
$('<div>',{class:'contact_user_name'}).appendTo('#new_contact');
var name_field = $('<input>',{
name:"contact_broker_fullname",
id:"contact_user_name",
}).appendTo('.contact_user_name');
var input_button = $('<input>',{
name:"submit",
type:"submit",
value:"Send"
}).appendTo('#new_contact');
var full_name=name_filed.val();//I'm not sure that this should be here at all.
input_button.on('click',function(){
ajax_send_contact(full_name);
return false;
});
});
And here is the ajax_send_contact(full_name) function:
$.ajax({
url:'../some.php',
type:'post',
data:{name:full_name},
success: function (response){
if (response) {
$('#success').append('<span>All right.</span>');
}
else{
$('#errors').append('<span>Something went wrong.</span>');
}
},
error: function () {
$('#errors').append('<span>ERROR!</span>');
}
});
I've read that when adding dynamically element to HTML they're not included into the DOM, so how can i operate with them. How i can get the value of the input so once the user click the Submit button the value is sent to ajax function. And I'm not asking only for this particular case but for the whole logic as I'm missing something quite important.
Thank you.
I don't know where you read this but it's not true.
Adding elements to your page is DOM manipulation.
In fact there is a lot of DOM manipulation in your ready function.
DOM manipulations are costly, try to reduce them by grouping operations :
var formHtml = '';
formHtml += '<div class="contact-form">';
formHtml += '<form id="new_contact">';
formHtml += '<div class="contact_user_name">';
formHtml += '<input type="text" name="contact_broker_fullname" id="contact_user_name">';
formHtml += '</div>';
formHtml += '<input type="submit" name="submit" value="send">';
formHtml += '</form>';
formHtml += '</div>';
$('#add_contacts').append(formHtml); // Only 1 DOM manip.
There are errors in your code :
$('#add_contacts').append('<div class="contact-from"></div>');
...
var name_field = $('<input>',{
And then :
$('<form></form>',{id:'new_contact'}).appendTo('.contact-form');
...
var full_name=name_filed.val();
'contact-from' then 'contact-form'.
'name_field' then 'name_filed'.
In your code, you get the value of your input#contact_user_name right after you created the form,
that is to say before the user had any chance to input something in it.
You have to do this in your click handler.
Pretty simple, set the data with the value of the field right before firing the request:
data: { name: $('.contact_user_name input').val() }
And you can remove var full_name=name_filed.val(), it would only get the value the field had at the moment it was created, and apparently that variable wouldn't be in scope when you actually need it.
The rest of your code looks okay.