$("#forcedcancel").on("click", function(e){
e.preventDefault();
$("#forceDialog").remove();
var forcedialog = "";
forcedialog += '<div id="forceDialog">';
forcedialog += '<h3>Reason for force cancelling the lesson</h3>';
forcedialog += '<p><textarea id="forcereason">A causa di </textarea><p>';
forcedialog += '<button id="submitforce" class="btn btn-primary">Submit</button><button id="cancelforce" class="btn btn-danger">Cancel</button>';
forcedialog += '<input type="hidden" id="dbv" value="'+bd+'">';
forcedialog += '</div>';
$('body').prepend(forcedialog);
});
$("body").on("click", "#submitforce", function(){
var data = {
bdv : $("#dbv").val(),
reason : $("#forcereason").text()
}
alert(data.reason);
});
div with id="forceDialog" is showing just fine. But when I am clicking Submit, I can't get the value from textarea with id="forcereason";
I tried to change the code to
$("body").on("click", "#submitforce", function(){
var data = {
bdv : $("#dbv").val(),
reason : $("body").closest("#forceDialog").find("#forcereason").text()
}
alert(data.reason);
});
But the only alert I am getting get is "A causa di ". The initial text inside the textbox. :(
First of all You need to use .val() instead of .text() to get the value.
I think you can u use directly $("#forcereason").val().Because id is unique
Related
I try to dynamically add an input field to a form. It works fine except one thing:
I try to fill a with $.each, but this only works for the first dynamically added if I add more, the stays empty..
the #add button is in the initial form:
append:
$('#add').click(function() {
i++;
$dynamic_field').append('' +
'<h1>Sensor '+i+'</h1> ' +
'<tr id="row'+i+'">
'<td><div class="form-group">\n' +
'<label for="InputSensorType">Sensor Type*</label>\n' +
'<select class="form-control" id="InputSensorType" name="sensorType[]"></select>\n'
'</div></td>\n +'
'<td>
<button type="button" name="copy" id="copy" class="btn btn-primary">Copy this sensor
</button></td><tr>');
Each:
var jsarray = <?php echo json_encode($sensors)?>;
$.each(jsarray, function (index, value) {
$('#InputSensorType').append(('<option value='+index+'>'+value+'</option>'));
});
Can anyone help me?
Try this
var jsarray = '<?php echo json_encode($sensors)?>';
var obj = jQuery.parseJSON(jsarray);
var data = '';
$.each(jsarray, function (index, value) {
data +='<option value='+index+'>'+value+'</option>';
});
$('#InputSensorType').append(data);
i have a data which were parsed from json, i display the data in a box like facebook's friends suggestion box. i want when the user click on any of the suggested users the request to be added to DB via ajax and its corresponding button disappears,everything is working just fine except the last thing(button disappears) instead the very first button in the list gets disappear, while im searching for a solution to my problem i came across something called closure but i reaaly couldn't know how to implement it in my code, another problem appeared when i tried to declare the listener anonymous function inside the loop was the data get inserted in the DB multiple times
(because its inside a loop), i know it might seems duplicated question but i just need someone pointing me the right place to declare my inner function,
my code looks like this
$(document).ready(function() {
var suggest = new XMLHttpRequest();
suggest.onreadystatechange = function() {
if (suggest.readyState === 4 && suggest.status === 200) {
var susers = JSON.parse(suggest.responseText);
for (var i = 0; i < susers.length; i += 1) {
var sphoto = '<div class="col-md-4 text-left "> <div id="fimage">';
sphoto += '<img width="50" height="50" src="user/';
sphoto += susers[i].activation + '/' + susers[i].pic + '"> </div> </div>';
var sname = '<div id="fname">' + susers[i].name + '</div>';
// here is the form im targetting to pull informtion from
var hidden = '<form id="fform"><input id="fnameh" name="name" type="hidden" value="' + susers[i].name + '" >';
hidden += '<input name="id" type="hidden" value="' + susers[i].id + '" >';
var fbutton = '<button id="addfriend"class="btn btn-info btn-xs pull-right text-center" type="submit" >Follow <span class=" glyphicon glyphicon-plus" aria-hidden="true"></span> </button></form';
var display = document.getElementById('fsuggest');
display.innerHTML += '<div class="scroller"><div id="fspace" > <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + sphoto + sname + hidden + fbutton +'</div></div>'
$('#addfriend').live('click', function(arg) {
return function() {
arg.preventDefault();
var data = $('#fform').serialize();
$.ajax({
data: data,
type: "post",
url: "addnew.php",
success: function(data) {
//make the text area empty
$('#addfriend').css("display", "none");
console.log(data);
}
}); // end of $.ajax
}(i); // end of inner function
}); // end of click listner
} //end of for loop
}
};
suggest.open('GET', 'box.php');
suggest.send();
}); // end of JQUERY ready
I am not sure why exactly you need closure here. The problem seems to be with the multiple form & button with same id.
All these buttons have same id so the forms. So
$('#addfriend').live('click', function(arg) {..}) has no reference to the particular button
Hope this change will help
Con-cat the value of iwith the id of the form & add an attribute data-id=i the button.
Beside instead of id add class addfriend to the button. So when this button will be clicked take the data-id value. Use this value to get the relevant form with id , & serialize that
var hidden = '<form id="fform_' + i + '"><input id="fnameh" name="name" type="hidden" value="' + susers[i].name + '" >';
hidden += '<input name="id" type="hidden" value="' + susers[i].id + '" >';
var fbutton = '<button data-id="' + i + '" id=""class=" addfriend btn btn-info btn-xs pull-right text-center" type="submit" >Follow <span class=" glyphicon glyphicon-plus" aria-hidden="true"></span> </button>';
Make below change to the click function.
Also reason of adding the event handler inside loop is not clear.
$('.addfriend').live('click', function(arg) {
arg.preventDefault();
var getDataId = $(this).attr('data-id') // get the data-id
var data = $('#fform_'+getDataId).serialize(); // get relevant form
$.ajax({
// rest of code
}); // end of $.ajax
})
Try to use jquery version above 1.9 to use the on method for event delegation
I made a few changes to your code.
With the new javascript, I believe most browsers support string interpolation natively (without any extra plugins or pre-compiling with babel for example) so you can just interpolate your variables within backticks ``.
Also, you seemed to be creating a form with the id of #fform and a button with the id of #addfriend for each iteration. The problem is that calling $('#fform') or $('#addfriend') will return an array with as many elements as you have users.
So I added an extra data-suser-id attribute with unique id's on those. I am not sure the code will work because I can't actually try it and changed quite a few things but let me know if you are getting closer to your solution.
$(document).ready(function() {
var suggest = new XMLHttpRequest();
suggest.onreadystatechange = function() {
if (suggest.readyState === 4 && suggest.status === 200) {
var susers = JSON.parse(suggest.responseText);
var limit = susers.length;
for (var i = 0; i < limit; i += 1) {
var sphoto = `<div class="col-md-4 text-left ">
<div id="fimage">
<img width="50" height="50" src="user/${susers[i].activation}/${susers[i].pic}">
</div>
</div>`
var sname = `<div id="fname">${susers[i].name}</div>`
// here is the form im targetting to pull informtion from
var hidden = `<form id="fform" data-suser-id='${susers[i].id}'>
<input id="fnameh" name="name" type="hidden" value="${susers[i].name}" >
<input name="id" type="hidden" value="${susers[i].id}">`
var mutalusers = `</form><div id="mutal" class="text-left">
<h6>
<div id="fmutal">
<?php echo $c = mutal(${susers[i].id}, $me, $db) ?>
</div>
</h6>
</div>`
var fbutton = `<button id="addfriend" class="btn btn-info btn-xs pull-right text-center" type="submit" data-suser-id='${susers[i].id}'>Follow <span class=" glyphicon glyphicon-plus" aria-hidden="true"></span> </button>`;
var display = document.getElementById('fsuggest');
display.innerHTML += `<div class="scroller">
<div id="fspace">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
${sphoto}
${sname}
${hidden}
${fbutton}
${mutalusers}
</div>
</div>`
// #live method is deprecated : http://api.jquery.com/live/
var addfriend_button = $(`#addfriend[data-suser-id=${susers[i].id}]`)
addfriend_button.on('click', function(arg) {
// return function(){
arg.preventDefault();
// the selector `#fform` doesn't seem to be unique to the current user's form data, so I added an data-attribute to make sure we are getting the correct form data
var data = $(`#fform[data-suser-id=${susers[i].id}]`).serialize();
$.ajax({
data: data,
type: "post",
url: "addnew.php",
success: function(data) {
//make the text area empty for the current user's `#addfriend` button
addfriend_button.html('done');
console.log(data);
}
}); // end of $.ajax
// }(i); // end of inner function : not sure why this inner function is necessary
}); // end of click listner
} //end of for loop
console.log(susers);
}
};
var suugestFile = 'box.php';
suggest.open('GET', suugestFile);
suggest.send();
}); // end of JQUERY ready
Created a basic input textbox and a button dynamically via javascript using some bootstrap css. On pressing the button I need to retrieve the value of the textbox. But its coming out to be empty (not undefined).
The doSearch function is where I need to pick up the value.
Here is the jsFiddle: http://jsfiddle.net/9u3kb6rk/3
Here is the code:
(function ($) {
function doSearch() {
alert($('#name').val());//this is empty?
}
$(document.body).on('click', '#go', function () {
alert('doing search');
doSearch();
});
$.fn.searchName = function () {
var caller = $(this);
var output = '';
output += '<div class="input-group ">';
output += '<span class="input-group-addon area" id="name" name="name">Name</span>';
output += '<input type="text" class="form-control" />';
output += '</div>';
output += '<div class="input-group">';
output += '<span class="input-group-btn">';
output += '<button class="btn btn-primary" type="button" id="go">Search</button>';
output += '</span>';
output += '</div>';
output += '</div>';
$(caller).html(output);
return this;
}
}(jQuery));
$(document).ready(function () {
$('#searchName').searchName();
});
The id must be in the input instead of in the span.
output += '<span class="input-group-addon area">Name</span>';
output += '<input type="text" id="name" name="name" class="form-control"
Your code updated.
I'm currently working on some input forms in JavaScript, and I've edited by script so that once the user enters the number of forces for a problem, new input text fields show up per number, also there is a button which is added at the end of that. The issue is when I try and click this button, I try and use the .map function to start all text field values into it and nothing is happening.
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
prompt("forces");
});
As you can see my forceRecording function is working and creates a new row with new text input fields per the numofforces but once I try clicking the forceButton to enter the values into my forces array nothing happens. Any idea what could be causing this?
You are missing the closing paranthesis around your code here
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){return $(this).val()
});
It should be like this
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val();
});
});
And don't use the id instead use a class name
$('#forceButton').click(function(){
forces=$(".newR").map(function(){
return $(this).val();
});
});
Apply the class to input field like this
<input type="text" name="forceItem" class="newR"/>
I have absolutely no idea what you're trying to achieve, but maybe this will help:
function forceRecording(numofforces, $this) {
var addRows = '<tr id="newRows">';
for (var i = 1; i <= numofforces; i++)
addRows += '<td>Force ' + i + ': </td><td><input type="text" name="forceItem" /></td>';
addRows += '<td><input type="button" class="button" id="forceButton" value="Add!" /></td></tr>';
$this.closest('tr').after(addRows);
}
$('#forceButton').click(function() {
forces = $(this).parent().parent().filter('input[name="forceItem"]').map(function() { return $(this).val(); });
});
By using relative references I am able to remove items which have been added to the list within a specfic part of the form. For example, by adding a requirement it can be deleted just from the requirement.
My issue is two fold:
Adding an item to references adds it to all three categories
When I try to add values to the other sections (qualifications) it says my input was blank.
http://jsfiddle.net/spadez/9sX6X/60/
var container = $('.copies'),
value_src = $('#current'),
maxFields = 10,
currentFields = 1;
$('.form').on('click', '.add', function () {
value_src.focus();
if ($.trim(value_src.val()) != '') {
if (currentFields < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
currentFields++;
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
value_src.focus();
$(this).parents('.line').remove();
currentFields--;
});
Is it possible to modify this code without repeating it for each section, by using relatively references such as "parent" for example. I want to use this same script for all three sections but have it so each list is independant.
I'm new to javascript so I was wondering if this is possible because I only managed to get it working on the delete.
You have to use this to get the current element. In your case this refers to the button which was clicked.
The next step is to get the input box which belongs to the button. E.g. $(this).prev(); like in this example:
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
http://jsfiddle.net/9sX6X/62/
The same is also true for your appending part. Your are appending your html to all three elements which match $('.copies'). Instead you have to try to get there from this.
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var copies = $(this).parent().prev();
http://jsfiddle.net/9sX6X/63/
I would suggest adding a wrapping div to each section.
<div class="section">
<h4>Requirements</h4>
<div class="copies"></div>
<div class="line">
<input id="current" type="text" name="content" placeholder="Requirement" />
<input type="button" value="Add" class="add" />
</div>
</div>
Then you can do this:
var $section = $(this).closest(".section");
$(html).appendTo($section.find(".copies"));
This will add to just the related .copies element instead of to all .copies as your code does now. A similar approach can be used for all other elements as well.