Clearing a div in Jquery using its i.d - javascript

I am trying to remove the user input and replace it with the original placeholder by using the empty() function.
Here is the jQuery file which takes input from user through a <form> and appends it to list with the template() structure:
var template = function(text) {
return '<p><input type="checkbox"><i class="glyphicon glyphicon-star"></i><span>' + text + '</span><i class="glyphicon glyphicon-remove"></i></p>';
};
var main = function() {
$('.form').submit(function() {
var text = $('#todo').val();
var html = template(text);
$('.list').append(html);
$('#todo').empty();
return false;
});
};
$(document).ready(main);
After the user submits their text and it is added to the list I want the 'form' input to empty so you can enter a new item with out deleting what you just typed.
Here is a snippet of the html file that jQuery is interacting with:
<form class="form">
<div class="form-container">
<input id="todo" type="text" class="form-input" placeholder="Add item">
</div>
<button type="submit" class="btn">+</button>
</form>
Why is the line
$('#todo').empty();
not removing the user input and returning it to the original placeholder?

The empty method doesn't delete the attributes or values but it removes the html inside an element. You should use val:
$('#todo').val('');//To empty the value
If you want to remove the placeholder too then use removeAttr method:
$('#todo').removeAttr('placeholder');

.empty() is for other use cases. From the docs...
Remove all child nodes of the set of matched elements from the DOM.
Instead, you can .val('') your <input />. Observe the following simplified example...
$('.form').submit(function() {
$('#todo').val('');
return false;
});
JSFiddle Link - demo
as an observation to your neighboring code you can also pass the event and call .preventDefault() in place of return false;. Alternatively, you can call reset() in your function block as such: this.reset() - reset demo with default behavior prevented.

Try this:
$('form').trigger("reset");
This is the most elegant and correct way since it will work when you have multiple and different type of inputs without needing to do any changes. Much better than trying to empty and resetting placehorders on all fields. This will make sure to set the fields to initial state (having placeholders set too).
Based on your code you could do:
$('.form').submit(function() {
// ...
$(this).trigger("reset");
// ...
});
See it working on an example form based on yours with more fields inputs and select here.
See JQuery reset Doc here: JQuery API Doc/reset

Related

Add items to drop-down box

I can't seem to find the correct syntax to get this working:
$.get('/templates/mytemplate.html', function (template) {
$(template).find('select').append($("<option />").val(0).text('Please select ...'));
$.each(dashboard.myArray, function () {
$(template).find('select').append($("<option />").val(this.Id).text(this.Text));
});
$('#new-items').append(template);
});
The template variable is just a string of html like:
"<form class="user-item">
<select class=".sc" name="context" />
<input type="hidden" name="id"/>
<input type="hidden" name="date"/>
<form>"
I've tried selecting the select item on name 'select[name=context]' and using a class selector like '.sc' as well ... none seem to work but I've got similar code working fine elsewhere. Very confused.
The problem is template is a string. in your case you are creating a new jQuery wrapper for that element every time and manipulating it but that does not actually change the contents of the string in template, it just changes another in memory object
You need to create a reference to a new jQuery wrapper for template then do the dom manipulation using that reference and at the end append it to the container element
$.get('/templates/mytemplate.html', function (template) {
var $template = $(template);
$template.find('select').append($("<option />").val(0).text('Please select ...'));
$.each(dashboard.myArray, function () {
$template.find('select').append($("<option />").val(this.Id).text(this.Text));
});
$('#new-items').append($template);
});
Demo: Problem, Solution
such code will work
var value = 'some_value',
text = 'some_text';
$('#id').append($('<option value='+value+'>'+text+'</option>'));
the reason your code it's not working is you are modifying a variable but don't assign the changes to variable
$(template).find('select').append($("<option />").val(0).text('Please select ...'));
this line never stores changes to template, it should be :
template = $(template).find('select').append($("<option />").val(0).text('Please select ...'));

Double insert after is permitted, but before doesnt

The following html markup
<div id="parent" class="parent">
<div id="child" class="child">
<input type="text" class="text"/>
<input id="submit" value="submit" type="submit" onclick="doThis()"/>
</div>
<div>
and JS code
function doThis(){
var span= document.createElement("span");
var parent=document.getElementById("parent");
var child=document.getElementById("child");
var submit=document.getElementById("submit");
child.insertBefore(span,submit.nextSibling);
myKeys=[];
myKeys.push(getAllKeyValuePair(submit));
span.innerHTML=myKeys;
}
function getAllKeyValuePair(obj){
var str="";
for(var key in obj){
try{
str=str+"{"+key+", "+obj[key]+"}";
}
catch(e){
console.log(key);
}
}
return str;
}
JSFIDDLE example.
It works fine and it's ok to click 2,3,...etcetera times on submit button, to click on duplcate of submit button... etc. But if we trying to replace child.insertBefore(span,submit.nextSibling); to child.insertBefore(span,submit); (i.e. insert span before submit button rather than after) we can only 1 time to click to submit button. Consequent clicks will caused exception. JSFIDDLE
The question obviously is why in the case of inserting before submit second and consequent clicks will causes exception, but in the case of insert after submit it's work fine. I think, that the reason of duplicating the submit button is not true.
When you do:
span.innerHTML = myKeys;
you're creating another element with id="submit". The next time you click the button,
var submit = document.getElementById("submit");
assigns this element to the variable, rather than the one in the original HTML. This element is not a child of child, so you get an error.
The version with nextSibling also creates these duplicate IDs, but the original submit element is earlier in the DOM than the added elements, so it gets returned by getElementById and you don't get an error. I don't think there's any guarantee that this will work, since duplicate IDs aren't permitted, but it's how most browsers work.
If you don't want the string returned by getAllKeyValuePairs to be parsed as HTML, assign it to span.innerText rather than span.innerHTML.

Dynamically adding form elements to dynamic form using jquery

I followed this example
How to use jQuery to add form elements dynamically
Is it possible to add form elements dynamically to the dynamically generated form?
This is my code:
<html>
<script src="jquery.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$('#addRow').click(function () {
$('<div/>', {
'class' : 'extraPerson', html: GetHtml()
}).hide().appendTo('#container').slideDown('slow');
});
$('#addAttribte').click(function () {
$('<div/>', {
'class' : 'extraAttribute', html: GetHtml1()
}).hide().appendTo('#extraAttribute').slideDown('slow');
});
})
function GetHtml() {
var len = $('.extraPerson').length;
var $html = $('.extraPersonTemplate').clone();
$html.find('[name=firstname]')[0].name="firstname" + len;
return $html.html();
}
function GetHtml1() {
var len = $('.extraAttribute').length;
var $html = $('.extraAttributeTemplate').clone();
$html.find('[name=attribute]')[0].name="attribute" + len;
return $html.html();
}
</script>
<div class="extraPersonTemplate">
<input class="span3" placeholder="First Name" type="text" name="firstname">
Add Attribute
<div id="extraAttribute"></div>
</div>
<div class="extraAttributeTemplate">
<input class="span3" placeholder="Attribute" type="text" name="attribute">
</div>
<div id="container"></div>
<i class="icon-plus-sign icon-white"></i> Add another family member</p>
</html>
I realise there will be issues regarding names of the newly added form elements, but at this point I just want to be able to dynamically add even just a line of text to a dynamically generated form.
Edit: Sorry, forgot to mention what the problem was; the page starts off with just a link saying "Add another family member". This will add the extraPersonTemplate. This template also has a "Add Attribute" link which adds an extra form field to this newly added field.
However when I click "Add Attribute", I'd expect it to add extraAttributeTemplate to the bottom of the dynamically added form, but nothing happens.
There are two specific issues.
IDs are supposed to be unique. Having an anchor with an id of addAttribute for every person isn't valid, and only the first element found in the DOM will have the event bound. This isn't a problem at the start because there's only one of them, but does become a problem later on once you start adding additional family members.
Events bound in the ready handler are only bound to elements that exist when the code executes. If you're going to be adding new elements that you want to have those events bound you need to use event delegation:
$(document).on('click', '.addAttribute', function() {
// add an attribute here
// I've changed from an ID to a class selector
// you'll need to find a way to get a reference to the correct elements from a specific anchor
});
I've put together a demo with the changes detailed above.

How to insert some values in all the html inputs of specific div, on page load?

I have multiple forms in a single page.
Every form is is in different <div>, I want to insert some values in html inputs, present in a specific <div>, Please tell what I am doing wrong?
function onLoadPopulateInputs(){
var digits = getDateTimeOnLoad();
console.log("DT "+digits)
$('.input').value = digits #I think here is someting wrong!!!
}
google.setOnLoadCallback(onLoadPopulateInputs);
My Input looks like this:
<input size="16" type="text" readonly>
$('#yourDiv > input').val(digits)
your selector is borked
function onLoadPopulateInputs(){
var digits = getDateTimeOnLoad();
console.log("DT "+digits);
var $yourDiv = $('#yourDiv');
$yourDiv.find('input').val(digits);
}
google.setOnLoadCallback(onLoadPopulateInputs);
I would add a class for div containing 'forms' :
<div class="formDiv">
<input />
....
</div>
<div class="formDiv">
<input />
....
</div>
JS
$('.formDiv').each(function(){
var $form = $(this);
$form.find('input').each(function(){
$(this).val(someValue);
});
});
Usage exemple http://jsfiddle.net/techunter/EzWpu/
Why this instead of just $('input') or $('#myDiv input') like proposed by other?
Well because here you can manage context and control everything. also you said you have multiple forms inside multiple div : "multiple" == make it generic and use class not id. If you need to edit a specific value maybe consider faster selection using ID or $('#myDiv input[name="myInputName"]) or equivalent
You need to use .val
$('.input').val(digits);
give your specific div an id and call an id selector..
function onLoadPopulateInputs(){
var digits = getDateTimeOnLoad();
console.log("DT "+digits)
$('#divID input').val(digits);
}
jquery method of setting a value of input is .val() and not .value

jQuery equivalent to `return document.getElementById(theVar)'

I've a javascript function
function $m(theVar){
return document.getElementById(theVar)
}
The problem with the above code is, the element I want to pass is generated by ajax so I need something like the .live() in jquery, unless it throws an error
How do I rewrite the above function in jQuery so that any DOM element generated later can also be detected.
Update:
When my page first load, it loads
1) ajaxupload.js with codes
function ajaxUpload(form,url_action,msg){
var id_element= "pop-con";
function $m(theVar){
return document.getElementById(theVar)
}
if($m(id_element)==null){
erro += "The element of 3rd parameter does not exists.\n";
}
}
2) index.php with codes
<div id="popupMargin">
<div class="close">x</div>
<div id="pop-con"></div>
</div>
<div id="ajaxGenerateMarkUp"></div>
3) now on the click of a button, the following markUp is added to the #ajaxGeneratedmarkUp div (mark-up generated through ajax)
<form onSubmit="return disableForm(this);" action="crop/wizecho_upload.php" method="post" name="f" id="wizecho" enctype="multipart/form-data">
<input id="file" type="file" name="file" onChange="return disableForm(this), ajaxUpload(this.form,'crop/wizecho_upload.php', '<br>Uploading image please wait.....<br>'); return false;"/>
</form>
Now on change of this input type file, made the call on in the javascript. Now it shows the error.
[Note: I only posted sections of code I think might affect my question]
Like this:
return $('#' + theVar)[0];
jQuery's selector can detected newly generated items:
$('#id');
So in your case:
var theVar = 'something';
$('#' + theVar); //returns a jQuery object of the select item
$('#' + theVar)[0]; //returns the first DOM object that jQuery finds with that id
I think you need to add a live call somewhere to detect the new AJAX-loaded button. This way, the button will be automatically bound to a handler that works OK as in other answers. From your comment I guess you are doing one of these:
In the AJAX-loaded button you already include some JS logic, that is not working (something like onclick="do_something").
You are binding the second button to a handler withoug the live method.
Here's a working example. Although it doesn't load contents via AJAX, it does load a dynamic button.
http://jsfiddle.net/marcosfromero/VKfKL/
Update: Another example that does load contents via AJAX and binds the newly created button with live:
http://jsfiddle.net/marcosfromero/h9RSC/

Categories