How to clear Input data from within JQuery Div - javascript

I have a simple form users can fill out and also add a new form to add multiple entries.
Everything works fine except when I enter data in the first set of inputs and click create new memberships it will take the data from the form and put it in the text boxes.
How can I stop that?
http://jsfiddle.net/811yohpn/2/
I have tried a couple different ways.
$('#education').find('input:text').val('');
$('#education: input').val('');
However that will clear all entries.

Call find on the newDiv, instead of all inputs within #education.
Updated fiddle
newDiv.find('input:text').val('');
var ed = 1;
function new_education() {
ed++;
var newDiv = $('#education div:first').clone();
newDiv.attr('id', ed);
var delLink = '<a class="btn btn-danger" style="text-align:right;margin-right:65px" href="javascript:deled(' + ed + ')" > Delete Education ' + ed + ' </a>';
newDiv.find('tr:first th').text('Education ' + ed);
newDiv.append(delLink);
newDiv.find('input:text').val(''); // <----------- added this
$('#education').append(newDiv);
}
function deled(eleId) {
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('education');
parentEle.removeChild(ele);
//ed--;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<legend>Education</legend>
<div id="education">
<div id="1">
<table border=3>
<tr>
<th colspan="4" style="background-color:#b0c4de;">Education 1</th>
</tr>
<tr>
<td>
<label>School Name</label>
<input type="text" name="schoolname[]" maxlength="30" size="30"/>
</td>
<td>
<label>Degree Type</label>
<input type="text" name="degreetye[]" maxlength="30" size="30"/>
</td>
<td>
<label>Degree Field</label>
<input type="text" name="degreefield[]" maxlength="30" size="30"/>
</td>
</tr>
</table>
</div>
</div>
<br/><a class="js-addNew btn btn-info" href="javascript:new_education()"> Add New Education </a>

You need to clear the inputs under the cloned element
newDiv.find('input').val('')
Demo: Fiddle
Your selectors are selecting all input elements within the #education container, that is not what you want. The newDiv variable refers to the newly created element so you can use that to find the input elements within in and then clear it

Related

Clear contents of multiple input fields?

Hi I am dynamically adding rows with a button and when I am finished entering information, I would like it to then clear the contents. The button "Add Pokemon" is the one I want to press and it should clear all the contents.
function addPokemon() {
var pokemonName = document.getElementById("pokemon-name-container");
pokemonName.innerHTML = document.getElementById("pokemon-names").value;
for (var i = 0; i < element.length; i++) {
if (element[i].value !== "undefined") {
pokemonArray.push(element[i].value);
}
}
console.log(pokemonArray);
for (var i = 0; i < pokemonArray.length; i++) {
document.getElementById("pokemon-container").innerHTML += "<li>" + pokemonArray[i] + "</li>";
}
document.getElementById("pokemon-name-container").value = "";
document.getElementById("move-name").value = "";
}
This is my function I am using. ^^
And below is my HTML vv
<div>
<table>
<tbody id="tbody">
<tr>
<td>
<div id="pokemon-name-container">
<p>Pok&eacutemon Name:</p>
<input type="text" id="pokemon-names" size="30">
</td>
</tr>
<tr>
<td>
<p class="moves">Moves:</p>
</td>
</tr>
<tr>
<td>
<input class="move-container" type="text" id="move-name" placeholder="Enter move here">
</td>
<td>
<input class="button-container" type="button" id="remove-btn" value="Remove Move" onclick="removeRow()">
</td>
</tr>
</tbody>
</table>
</div>
<div>
<input type="button" class="add-move-button" id="add-move-button" value="Add Move" onclick="addRow()">
</div>
<div>
<input type="button" class="add-pokemon-button" id="add-pokemon-button" value="Add Pokémon" onclick="addPokemon()">
</div>
You could put to all the inputs you create a unique class that defines them under a parent with a unique id. Then use inside the function of javascript the next pice of code const childs = document.querySelectorAll('#idParent.classChilds') this querySelectorAll is kind of like the getElementsById but uses selectors of CSS so it's more powerfull. The querySelectorAll returns you a NodeList of all the elements that matches de DOM with the CSS query.
Then you would only need to do something similar to this using functional programming:
const childs = document.querySelectorAll('#idParent .classChilds')
childs.forEach(child=>{
child.value = ""
})
I'm not sure if this code works (I'm not with an code editor and a browser to check if there isn't mistakes), as I said, you could do something similar to it
HOPE IS HELPFULL
FYI, try to avoid the selectors like getElementById or getElementsByClass....
Try to use this:
document.querySelector('CSS SELECTOR') // GIVES YOU THE FIRST MATCH OF THE CSS SELECTOR
document.querySelectorAll('CSS SELECTOR') // GIVES YOU A NODELIST WITH ALL MATCHES

How to execute JS when page load instead of event trigger?

I'm trying to come up with a JS that detects number of empty fields in my form. I have 3 fields. If JS counted 2 or more empty fields, JS will change the css color to red. If JS counted 1 empty field, JS will change the css color to green. This works fine when i enter data into the input field. However, when i load the page with data already inside the two fields, the color still remain red. How can make the JS check if there already values in the input box and switch color accordingly based on number of empty fields when the page is loaded?
Below is when the page is loaded but showing red even though there are only 1 empty field.
I have checked all forums but no answer to my problem
'''HTML'''
<table>
<tr></tr><td> Field 1: <input class="user_field" type="text" name="1[user_fname]" value="1" autofocus/></td></tr>
<tr><td>Field 2: <input class="user_field" type="text" name="1[user_lname]" value="2"/></td></tr>
<tr><td>Field 3: <input class="user_field phone" type="text" name="1[user_mobile]"/></td></tr>
<tr><td> </td></tr>
</table>
<div id="result"></div>
<div class="containerbox">
<div id="centerbox1" style="background-color: #FF6C60;">
<div class="value">
<p><span style="color: #fff ;font-weight:bold; font-size:36px">test</span></p>
</div>
</div>
</div>
</div>
'''JS'''
$(document).ready(function(){
$('.user_field').blur(function() {
var text = "field(s) empty";
var count = $('.user_field').not(function() {
return this.value;
}).length;
$('#result').html(count + " " + text);
//*alert(count);
var udata = count;
if (udata > 2){
document.getElementById("centerbox1").style.backgroundColor = '#FF6C60';
}
else
if (udata <= 2)
{
document.getElementById("centerbox1").style.backgroundColor = '#99C262';
}
});
});
I expected the background color to be green as there are 2 data in the fields when the page is loaded but the page shows color red.
Move the function out of the blur event handler, and call it from the ready() handler:
$(document).ready(function() {
// Function of its own
function checkFields() {
var text = "field(s) empty";
var count = $('.user_field').not(function() {
return this.value;
}).length;
$('#result').html(count + " " + text);
//*alert(count);
var udata = count;
$('#centerbox1').css('background-color', udata > 2 ? '#FF6C60' : '#99C262');
}
// Set up event handler
$('.user_field').blur(checkFields);
// Call function
checkFields();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr></tr>
<td> Field 1: <input class="user_field" type="text" name="1[user_fname]" value="1" autofocus/></td>
</tr>
<tr>
<td>Field 2: <input class="user_field" type="text" name="1[user_lname]" value="2" /></td>
</tr>
<tr>
<td>Field 3: <input class="user_field phone" type="text" name="1[user_mobile]" /></td>
</tr>
<tr>
<td> </td>
</tr>
</table>
<div id="result"></div>
<div class="containerbox">
<div id="centerbox1" style="background-color: #FF6C60;">
<div class="value">
<p><span style="color: #fff ;font-weight:bold; font-size:36px">test</span></p>
</div>
</div>
</div>
</div>

js how to change id inside cloned form with its own new id

I have a section called duplicator1. I want to clone that section and it works but my issue is when section is cloned id of elements are same, so how can I change id when section is cloned.
My js functions
var countCopies1;
var clone ;
function duplicate() {
var original = document.getElementById('duplicater1');
clone = original.cloneNode(true);
var countCopies = $('body').html().split('duplicater').length;
clone.id = "duplicater"+countCopies;
original.parentNode.appendChild(clone);
countCopies1 = countCopies;
}
My table with id duplicater1. When I duplicate it id changes to duplicater2, duplicater3 and so on, but my id customer, project, post, hours stay the same in new duplicated table. How can I change them & I need in duplicater2 id customer1, project1, post1, hours1.
I will be thankful if u help me!
<div id="duplicater1">
<br></br>
<table class="table table-bordered">
<thead>
<tr>
<th style="width:16%;text-align:center">{Customer}</th>
<th style="width:16%;text-align:center">{Project}</th>
<th style="width:16%;text-align:center">{Activity}</th>
<th style="width:16%;text-align:center">{Hours}</th>
<th style="width:16%;text-align:center">{Comment}</th>
<th style="width:5%"> </th>
</tr>
</thead>
<tbody>
<td>
<div class="form-inline" style="text-align:center"><select style="width:200px" id="customer" class="form-control" onchange="getCustomerAddWork(this)">{CUSTOMERS}</select></div>
</td>
<td>
<div class="form-inline" style="text-align:center"><select style="width:200px" id="project" class="form-control" onchange="getProjectAddWork(this)"></select></div>
</td>
<td>
<div class="form-inline" style="text-align:center"><select style="width:200px" id="post" class="form-control"></select></div>
</td>
<td>
<div class="form-inline" style="text-align:center">
<div class="form-group">
<input type="number" class="form-control" id="hours" placeholder="{Hours}">
</div>
</div>
</td>
<td>
<div class="form-inline" style="margin-bottom:1em;text-align:center">
<div class="form-group">
<textarea class="form-control" id="comment" placeholder="{Comment}"></textarea>
</div>
</div>
</td>
<td>
<button type="button" class="btn btn-danger" style="width:70px"
onclick="Remove()">{Delete}</button>
</td>
</tbody>
</table>
</div>
</div>
<div class="container-fluid bg-2 text-center" style="margin-top:5em;margin-bottom:3em;">
<button type="button" class="btn btn-success" onclick="duplicate()">{Add}</button>
<button type="button" class="btn btn-info" onclick="AddWork()">{Submit}</button>
<button type="button" class="btn btn-primary" onclick="Redirect()">{Cancel}</button>
</div>
</form>
Since you have jQuery, I would do something like this:
var original = $("#duplicater1");
function duplicate() {
var countCopies = $("[id^='duplicater']").length + 1;
var cloned = original.clone();
var cloned.attr("id", "duplicater" + countCopies);
$(cloned).find("[id]").each(function(){
var current = $(this);
var currentId = current.attr("id");
var ids = $("[id='" + currentId + "']");
if(ids.length > 1 && ids[0]==this){
var newId = currentId.substring(0, currentId - 1);
current.attr("id", newId + countCopies);
}
});
original.parent().append(cloned);
}
My table with id duplicater1. When I duplicate it id changes to
duplicater2, duplicater3 and so on, but my id customer, project, post,
hours stay the same in new duplicated table. How can I change them & I
need in duplicater2 id customer1, project1, post1, hours1.
Yes, as duplicate identifiers are not good markup you should indeed change them.
However, duplicate identifiers within unique identifiable containers are functionally not an issue (Though still should be changed).
To address your actual question, yes you can write a loop that goes through each element within the duplicator container and append a number to it and I'm sure there are answers showing you how to and they are perfectly fine.
I would however try to address the duplicate identifier issue in another way that doesn't require maintaining code to do this.
An approach I have been using in numerous web projects in those type of scenarios is to use data-id as an attribute to identify the containers and to allow you to group them as well as the elements inside.
Note, you can use classes or data-xxx or what ever takes your fancy, I personally just prefer data-id for these cases
Instead of using <div id="duplicater1/2/3"> just use <div data-id="duplicater"> to identify the "type" of component/form you are working with.
Inside, do the same with each element, such as <select data-id="customer"> or <select data-id="project">
This solves the cloning problem all together as you can now clone each
duplicator without the need to rename anything at all and you don't
need to maintain custom code renaming element identifiers
In regards to the bound events, you don't have to worry about them either as each element when it raises an event such as getProjectAddWork(this) is already within context.
Say you trigger the getProjectAddWork(this) event and need to get to your duplicator container your are in, you can simple do something similar to $(this).closest('[data-id="duplicator"]'); or to get to the outer form $(this).closest('form'); etc..
Sure, you can achieve the same by only renaming the duplicator id as you already do and then do $(this).closest('#duplicator'); but in my humble opinion I rather prevent duplicate identifiers and not having to maintain code to rename identifiers as well as base selectors on contextual awareness within their respective "component"
I use jQuery as you tagged your question with it but you can do the same with just plain JavaScript

How to traverse dom tree from a list of elements

I have HTML snippet which looks like this. I generate this snippet multiple times form the backend. When I click the Save button, I catch which Save button was clicked using $(this) selector. Now I want to grab the attribute item-id of the corresponding Save button. I have the following jquery code snippet. But it does not work. I have tried to look but I don't know where the error is.
<td><input type="text" size="10" value="val1" item-id="id1"></td>
<td><input type="text" value="val2" size="4"></td>
<td>
<button class="btn btn-primary save-btn">Save</i></button>
</td>
Here is the jquery snippet
$(".save-btn").click(function(){
var ems = $(this).parent().siblings();
var item_id = ems[0].child().attr("item-id");
}
click doesn't work on dynamically added elements.You need to use on('click'). Also there is no method .child() so you need to use .children().first().
This is the corrected code:
$(document).on('click', '.save-btn', function(){
var ems = $(this).parent().siblings();
var item_id = ems.children().first().attr("item-id");
});
// The text
var text="";
text += "<td><input type=\"text\" size=\"10\" value=\"val1\" item-id=\"id1\"><\/td>";
text += "<td><input type=\"text\" value=\"val2\" size=\"4\"><\/td> ";
text += "<td>";
text += " <button class=\"btn btn-primary save-btn\">Save<\/i><\/button>";
text += "<\/td>";
// Adding the text to html
$('body').html(text);
$(document).on('click', '.save-btn', function(){
var ems = $(this).parent().siblings();
console.log(ems);
var item_id = ems.children().first().attr("item-id");
alert(item_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
better replace item-id="id1" to data attribute html5 data-id="id1" then replace code attr('item-id') to data('id')...
$(document).on('click','.save-btn', function(){
var ems = $(this).parent().siblings(),
item_id = ems.eq(0).children('input').attr("item-id");
alert(item_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" size="10" value="val1" item-id="id1"></td>
<td><input type="text" value="val2" size="4"></td>
<td>
<button class="btn btn-primary save-btn"><i>Save</i></button>
</td>
</tr>
</table>

How to create id of input box of form

I have this form.
<table><tr><td>
<FORM>
<label> ID </label></td>
<td>
<input type=text id="inputp1_id" size=24 class="text">
</td></tr>
<tr><td>
<label>Type</label></td><td><select id="inputp1_type" name="inputp1_type"><option value="text">Text</option><option value="integer">Integer</option><option value="float">Float</option><option value="list_values">List of values</option>
<option value="range">Range</option><option value="selection_collapsed">Selection (collapsed)</option><option value="selection_expanded">Selection (expanded)</option><option value="subimage">Subimage selection</option>
<option value="polygon">Polygon selection</option><option value="horizontal_separator">Horizontal separator</option></select>
</td></tr>
<tr><td> <label > Description</label></td> <td><input type=text id="inputpi_description" size=24 class="text"> </td><!--style=" width:300px; height:20px;"-->
</tr>
<tr><td> <label>Value</label></td><td> <input type="text" name="inputp1_value" id="inputp1_value" class="text" size=24></td></tr>
<tr><td> <label > Info (help)</label></td><td>
<input type=text id="input1_value" size=24 class="text"></td></tr>
<tr><td><label > Visible?</label></td><td><input type="checkbox" name="inputp1_visible" id="inputp1_visible"></td></tr></table>
<!--</form>--></div>
But (it's possible?) can create the id's input box?
Because the variable these are "numbered".
For example the first id in the form is inputp1_id but the number i want use how variable.
It's possible create the id with the Javascript o Jquery?
l=3
Id='inputp' +l+'_id'
After this create the input text has the id=inputp3_id
Here is one example on how to generate html contents dynamically with jquery and javascript. Both methods, although they look similar, give a bit different results: jquery generates one additional <tbody> tag, while javascript inserts the new rows directly to <table>. I recommend you to inspect the result in the Firefox's DOM Inspector by pressing Ctrl+Shift+I. IT's very handy and effective tool. And here is the algorythm:
var i=0; // this is simple counter
function generate_row_dynamically_in_jquery() {
i++;
var new_row = $('<tr/>');
var new_cell1 = $('<td>ID <input type="text" name="inputp'+i+'_id" id="inputp'+i+'_id" size="24" class="text"/></td>');
var new_cell2 = $('<td>Visible? <input type="checkbox" name="inputp'+i+'_visible" id="inputp'+i+'_visible"> </td>');
new_row.append(new_cell1).append(new_cell2);
$('#table1').append(new_row);
}
function generate_row_dynamically_in_javascript() {
i++;
var new_row = document.createElement('tr');
var new_cell1 = document.createElement('td');
new_cell1.innerHTML = 'ID <input type="text" name="inputp'+i+'_id" id="inputp'+i+'_id" size="24" class="text"/>';
var new_cell2 = document.createElement('td');
new_cell2.innerHTML = ' Visible? <input type="checkbox" name="inputp'+i+'_visible" id="inputp'+i+'_visible">';
new_row.appendChild(new_cell1);
new_row.appendChild(new_cell2);
document.getElementById('table1').appendChild(new_row);
}
& #jsfiddle

Categories