I'm trying to create to remove a form element using javascript. When I remove an element, it removes the topmost element. I'm trying to remove a specific element. Here is a link to the page and below is the code. Any help would be appreciated, thanks!
http://training.cvrc.virginia.edu/test.html
<script type="text/javascript">
var patient = 0;
function add_patient() {
patient++;
var add= document.createElement('patientdiv');
add.innerHTML += "<div id=removepatient></br>Patient "+patient+" Name/ID:<input type=text name=patients[] ><input type=button id=more_fields onclick=removepatient(); value='Remove' ></div>";
document.getElementById('patientdiv').appendChild(add);
return false;
}
function removepatient() {
var elem = document.getElementById('removepatient');
elem.parentNode.removeChild(elem);
return false;
}
</script>
<div id=patientdiv></div>
<input type=button id=more_fields onclick=add_patient(); value='Add Patient'></br></br>
You should generate a unique ID for each element you are adding to the page.
You can use a variable and increment this variable each time an element is added. In your exemple, the variable 'patient' is enough.
add.innerHTML += "<div id=removepatient_"+patient"></br>Patient "+patient+" Name/ID:<input type=text name=patients[] ><input type=button id=more_fields"+patient+" onclick=removepatient("+patient+"); value='Remove' ></div>";
You must also add a param to your delete function :
function removepatient(patient) {
var elem = document.getElementById('removepatient_'+patient);
elem.parentNode.removeChild(elem);
return false;
}
I hope it helps you
Related
I have to add an id to an element. An engine generates the HTML... I have no access to it. It generates random IDs as such:
<input id="5352Adkdie4929888a">
I want to grab the first instance of "<input id=" and replace the ID it has with
the ID it has + DatePicker.
Example:
<input id="5352Adkdie4929888a DatePicker">
How would I go about doing this?
My code so far:
function addID(){
var html= document.documentElement.innerHTML;
var start= '<input id="';
var end= '"'
var htmlIWant=html.substring(html.indexOf(start) + start.length), html.indexOf(end)-1 + 'DatePicker';
}
Am I on the right track? How do I actually replace the HTML? Thanks!
This is a pure javascript solution as per your requirements.
Assuming that your page will have many input tags and some of them will be without ID attribute below is a solution you can try.
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++)
{
if (elements[i].type == "text" && elements[i].hasAttribute("id"))
{
var id = elements[i].getAttribute("id");
elements[i].setAttribute("id", id + "10");
break;
}
}
Grab the first input inside the element using
$('input:first-child').attr('id','whateverIdName');
If you have to catch first input box that has id attribute, you should do :
$("input[id]")[0]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a div which is
<div class="add1"></div>
I want the add1 become add+thenumber of length example:
var n= $('.add1').length + 1;
$('.add1').click(function(){
so what I did is
$('.add+n').click(function(){
but it doesnt work, please help me :(
You can store the number in a data attribute and increment on every click.
Change the class attribute from the data attribute value.
HTML
<div id="myDiv" data-num='1' class="add1">click me</div>
JS
document.getElementById('myDiv').addEventListener('click', function(){
var num = Number(this.getAttribute('data-num'));
num++;
this.setAttribute('data-num', num)
this.setAttribute('class', 'add' + num);
});
Try this
$('.add'+n).click(function(){
});
the n needs to be outside of the quotes else it will interpret it as a string. Like so:
$('.add' + n).click(function(){
At first i read your question wrong and i thought you wanted to change the div's class accordingly. Which you could do like this:
var n = 1;
var n= $('.add'+1).length + 1;
$('.add' + n).click(function(){
$(this).attr('class', 'add' + n); //for if you also want to change the class of the div
});
Make use of .addClass() to add and .removeClass() to remove classes
$('.add1').click(function(){
var n= $('.add1').length + 1; //reads n
$(".add1").addClass("add"+n); //adds new class
$(".add"+n).removeClass("add1"); //removes existing class
});
Here is the example: https://jsfiddle.net/danimvijay/ssfucy6q/
If you want to select the class with combination of a variable, use $('.add'+n) instead of $('.add+n').
$('.add'+n).click(function(){
//place code here
});
Here is the example: http://jsfiddle.net/danimvijay/a0j4Latq/
Here it is!! try this .. I code following exactly you need.
<input type="text" style="display:none;" name="qty" value="0" />
<p id="inc" class="">It's class will be Increased[concate with number]</p>
<input type="button" id="btn" name="btn" value="increase"/>
Now following is Main script that will help you ..
var incrementVar = 0;
$(function() {
$("#btn").click(function() {
var value = parseInt($(":text[name='qty']").val()) + 1;
$(":text[name='qty']").val(value);
$('#inc').removeClass('a' + (value-1));
$('#inc').addClass('a' + value); // I believe class names cannot start with a number
incrementVar = incrementVar + value;
});
});
i posted this code also on www.codedownload.in
Thank You.
I am using dynamically added textbox (class name is myclass) and need to validate all textboxs. My code is here. This coding is working for only first textbox. If i add new text box, the code is not working. I don't know how to write the event binding in each(function())
$('.myclass').each(function() {
$(this).rules('add', {
required: true,
messages: {
required: "Required input"
}
});
});
HTML CODE
<div id="TextBoxesGroup">
<div id="Div1">
<input type='text' value ='' class='myclass' />
</div>
</div>
<input type="button" name="add" id="addButton" value="Add">
$(document).ready(function(){
var counter=2;
$("#addButton").click(function() {
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'Div' + counter);
var texthtml = "";
texthtml += "<input type='text name='fieldname[]' class='myclass' value='' />";
newTextBoxDiv.after().html(texthtml);
newTextBoxDiv.appendTo("TextBoxesGroup");
});
The each function can only be applied to elements already existing in you DOM. Elements which are added later will not be affected. You need to apply rules() to them after they are created. Like this:
$("#addButton").click(function() {
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'Div' + counter);
...
$( newTextBoxDiv ).rules( ... );
});
Ps: to get more readable code, try to encapsulate your functionality into functions. Like
function addRulesToElement( element ) {
$( element ).rules( ... );
}
You can then call this function from your each() loop and the #addButton click-handler without repeating yourself.
I am trying to add a new textbox when add button is onclick using JavaScript. Here is my HTML:
htmlStr += "<div id='filterContent' style='width:100%;text-align:center;'>";
htmlStr += "<input id='startLoc' type='text' />";
htmlStr += "<input id='endLoc' type='text' />";
htmlStr += "<input id='addLoc' type='button' value='Add' onClick='addTextBox()' />";
htmlStr += "</div><br/>";
And here is my JavaScript to add a new textbox when button is onClick:
function addTextBox(){
var element = document.createElement("input");
element.setAttribute("type", "text");
element.setAttribute("value", "");
element.setAttribute("name", "Test Name");
//element.setAttribute("style", "width:200px");
var foo = document.getElementById("filterContent");
foo.appendChild(element);
}
It works perfectly to add as many textbox as I want. But somehow the textbox created share the same id. I wonder is that possible to add many textbox with different ID each time when the button is onClick?
Thanks in advance.
var aa=Math.random();
<input id='addLoc"+aa+"' type='text' />
User math.random to generate random id's for a textbox
Using your current setup you could keep track of an id increment in a global:
//outside function
var idIndex = 1;
function addTextBox(){
var element = document.createElement("input");
element.setAttribute("type", "text");
element.setAttribute("value", "");
element.setAttribute("name", "Test Name");
element.setAttribute("id", "addLoc" + idIndex++);
element.setAttribute("style", "width:200px");
element.onclick = function()
{
//do something
}
var foo = document.getElementById("filterContent");
foo.appendChild(element);
}
EDIT: To answer the question in this answer's comments. It is certainly possible to add a different onclick handler for every new textbox (although you're probably better off designing your handlers so you can use a single handler for all but if you wanted for some reason to use a different one you could bind an anonymous function to the handler, I have added an approach above).
EDIT2: Regarding the second question in the path there are two approaches you could use. Instead of calling the separate functions getFirstPath() getSecondPath() etc. individually, you could have a single function called getPath() and pass the index to it as a parameter:
var getPath = function(index) {
switch(index)
{
case 1:
return getFirstPath();
break;
case 2:
return getSecondPath();
break; //and so on.
}
}
And then your onclick would look like this:
element.onclick = function()
{
getPath(index);
}
I have a application which you can access here. If you open the application please click on the "Add" button a couple of times. This will add a new row into a table below. In each table row there is an AJAX file uploader.
Now the problem is that if I click on the "Upload" button in any row except the first row, then the uploading only happens in the first row so it is only uploading the first file input only.
Why is it doing this and how can I get it so that when then the user clicks the "Upload" button, the file input within that row of the "Upload" button is uploaded and not the first row being uploaded?
Below is the full code where it appends the file AJAX file uploaded in each table row:
function insertQuestion(form) {
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'></tr>");
var $image = $("<td class='image'></td>");
var $fileImage = $("<form action='upload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startUpload();' >" +
"<p id='f1_upload_process' align='center'>Loading...<br/><img src='Images/loader.gif' /><br/></p><p id='f1_upload_form' align='center'><br/><label>" +
"File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label><input type='submit' name='submitBtn' class='sbtn' value='Upload' /></label>" +
"</p> <iframe id='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px solid #fff;'></iframe></form>");
$image.append($fileImage);
$tr.append($image);
$tbody.append($tr);
}
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + '<label>File: <input name="fileImage" type="file"/><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
UPDATE:
Current Code:
var $fileImage = $("<form action='upload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startUpload(this);' >" +
"<p class='f1_upload_process' align='center'>Loading...<br/><img src='Images/loader.gif' /><br/></p><p class='f1_upload_form' align='center'><br/><label>" +
"File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label><input type='submit' name='submitBtn' class='sbtn' value='Upload' /></label>" +
"</p> <iframe class='upload_target' name='upload_target' src='#' style='wclassth:0;height:0;border:0px solclass #fff;'></iframe></form>");
function stopUpload(success, source_form){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
$(source_form).find('.f1_upload_process').style.visibility = 'hidden';
$(source_form).find('.f1_upload_form').innerHTML = result + '<label>File: <input name="fileImage" type="file"/><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
$(source_form).find('.f1_upload_form').style.visibility = 'visible';
return true;
}
Why am I getting an error on this line below:
$(source_form).find('.f1_upload_form').style.visibility = 'visible';
Without seeing the full cose, your problem seems to be that you are working with ID's, which must be unique within one document. If several elements are using the same ID, in the best case a browser will use the first one (which it does here), in the worst case nothing will work.
When adding a new upload form, you have to give the elements in it unique ID's. You could do that simply by attaching a counting variable to window, e.g.
$(document).ready( function(){ window.formCount=0; } );
You could then add that number to the ID of the newly added form.
Apart from this, by using the this variable, you can carry a reference to the correct form through, e.g. like onsubmit='startUpload(this);' as well as function startUpload(f){...
You should then be able to access things within the form using $(f).find(...).
There are many ways to make this work and solve the issue of multiple ID's. What I would do: var $fileImage = $("<form action... In this form where it says id I would instead use class. Then as above, change the onsubmit (in the same line) by adding "this" to its brackets. Then change the function startUpload as here:
function startUpload(source_form){
$(source_form).find('.f1_upload_process').css('visibility','visible');
$(source_form).find('.f1_upload_form').css('visibility','hidden');
return true;
}
You have to do the same thing for other functions where you want to access something inside the form that is sending a file. Pass a reference to the form to the function using this in the function call's brackets, then access things inside the form as I showed above.