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.
Related
I have an input-text. If you type something, the text appears below (see code snippet).
Now, I need to do the same with a previous step: clicking a button (preferably a checkbox) to append/remove all. Here is my failed idea: DEMO (it appends the input text, but when you type, text won't apear below like it does on my code snippet).
I feel like the function to add text below does not work because there is a problem with selecting the appended element. How do I do this?
Any more simple idea to do this would be great
var name1 = document.getElementById('name');
name1.addEventListener('input', function() {
var result = document.querySelector('.X');
console.log(this.value );
result.innerHTML = this.value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>What is your name? </label><input type="text" id="name">
<p>Your name is: <span class="X"></span></p>
Put your first part of the snippet into appending logic while clicking the add button. As in your codes, the input box is appended to the document after its listener being attached.
if (!added) {
$content = $(NewContent).appendTo('.firstappend');
// attach listener after input box actually exists!
var name1 = document.getElementById('A');
name1.addEventListener('input', function() {
var result = document.querySelector('span.Y');
console.log(this.value );
result.innerHTML = this.value;
});
}
$(function() {
let NewContent = '<div class="added">' +
'<p>' +
'<label>What is your name? </label>' +
'<input type="text" id="A">' +
'</p>' +
'<p>Your name is: <span class="Y"></span></p>' +
'</div>';
$(".addremove").on('click', function() {
if ($(".added").length) {
$(".added").remove();
} else {
$(".firstappend").append(NewContent);
}
});
$(document).on('change keyup', '#A', function(event) {
$("span.Y").html($(event.currentTarget).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toadd">
<button type="button" class="addremove">Do you have a name?</button>
</div>
<div class="firstappend"></div>
as from the DEMO you included,
appended elements to document cannot be invoked explicitly, since you're using jQuery, you can do this
$(document).on('change keyup', '#A', function(event) {
$("span.Y").html($(event.currentTarget).val());
});
I have to use multiple dropzone areas to upload images. I have used the jQuery append() function to dynamically create the div.
The problem is that the dynamically created dropzone is not initialized and therefore not working.
Just make sure to call the plugin on that newly appended element. The problem is the plugin gets attached to only elements which were present initially.
So, call the plugin once again after you append the element so, it gets attached and works again.
Here is the script i have used to do the same.
I have changed the dynamically created input type text's name field by using the querySelector. The querySelector returns the reference of the elements which have custom attribute i have used data-tagline.
Dropzone.options.myDropzone = {
init: function() {
this.on("addedfile", function(file) {
_ref = file.previewTemplate.querySelector('[data-tagline]');
_ref.name = "This is my New name attribute of element";
})
},
previewTemplate:"<div class=\"dz-preview dz-file-preview\">\n "+
"<div class=\"dz-details\">\n "+
"<div class=\"dz-filename\"><span data-dz-name></span></div>\n "+
"<div class=\"dz-size\" data-dz-size></div>\n "+
"<img data-dz-thumbnail class=\"img-responsive img-thumbnail\" />\n "+
"<input type=\"text\" data-tagline />"+
"</div>\n "+
"<div class=\"dz-progress\">"+
"<span class=\"dz-upload\" data-dz-uploadprogress></span>"+
"</div>\n "+
"<div class=\"dz-success-mark\"><span>✔</span>"+
"</div>\n "+
"<div class=\"dz-error-mark\"><span>✘</span>"+
"</div>\n "+
"<div class=\"dz-error-message\"><span data-dz-errormessage></span>"+
"</div>\n"+
"</div>",
};
<div id="my-dropzone" class="dropzone" action="upload.php"></div>
In your script you need a function to create the form for dropzone, and then execute the function Dropzone.discover()
function add_dropzone() {
const drop_zone = document.createElement("form");
drop_zone.setAttribute("class","dropzone");
drop_zone.setAttribute("action","url_to_upload_files/");
drop_zone.setAttribute("id","my_dropzone");
//find a div where you want to add your dropzone
document.getElementById("div_for_dropzone").appendChild(drop_zone);
// this function will find the class="dropzone" tag and load it.
Dropzone.discover();
}
then in your html you just need to add a div with the id="div_for_dropzone"
dynamically create dz element:
var d='<div id="dzFormDiv">';
d+=' <form ';
d+=' class="dropzone"';
d+=' id="my-awesome-dropzone">';
d+=' <input type="hidden" id="dztoken" name="dztoken"> ';
d+=' <input type="hidden" id="dzt2" name="dzt2"> ';
d+=' </form> ';
d+=' <div id="dsbw">';
d+=' <button id="btnRemoveAlldz">clear</button>';
d+=' </div> ';
d+='</div> ';
append to div somewhere
$("#uploads").prepend(d);
start instance
myAwesomeDropzone = new Dropzone("#my-awesome-dropzone", { url: "../cgi/newUploader.exe"});
add options
Dropzone.options.myAwesomeDropzone = {
init: function () {
var myDropZone = this;
$("#btnRemoveAlldz").click(function () {
myDropZone.removeAllFiles();
}
);
myDropZone.on("complete", function (file) {
if(this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
consol.log("completed upload");
}
});
myDropZone.on("sending", function (file) {
// do something before uploading
});
},
error: function(){
// call error handling function
},
success: function(file,r){
// called after EACH successfull upload
file.previewElement.classList.add("dz-success");
if(r.indexOf("ok")>-1){
console.log("success");
}else{
console.log(r);
}
}
};
A bit late to the party but they thought about it. As stated in the usage part of the documentation:
Alternatively you can create dropzones programmaticaly (even on non form elements) by instantiating the Dropzone class
// Dropzone class:
var myDropzone = new Dropzone("div#myId", { url: "/file/post"});
You may have to create an element and set some properties manually.
var form = document.createElement('form');
form.classList.add('dropzone');
form.method = 'post';
form.action = '/file/post';
document.getElementById('parent').appendChild(form);
new Dropzone(form);
Don’t forget to specify an url option if you’re not using a form element, since Dropzone doesn’t know where to post to without an action attribute.
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
I'm looking for help to rename the name attributes of some fields created dynamically.
Now, my code assigns new values to the added fields (it increments according to the length of the div) but the problem appears when I delete a field, I don't know how to rename the remaining according to the number of fields deleted.
jQuery:
$(document).ready(function () {
$("#add").click(function () {
var intId = $("#reglas div").length;
var fieldWrapper = $('<div></div>', {
class: 'fieldwrapper',
id: 'field' + intId
});
var fPath = $('<input align="left" type="text" placeholder="Path" class="reglas_wrapper" id="path" name="field1_' + intId + '" required /> ');
var fTTL = $('<input type="text" class="reglas_wrapper" placeholder="TTL" id="ttl" name="field2_' + intId + '" required />');
var removeButton = $('<input align="right" type="button" id="del" class="remove" value="-" /> <br><br>');
removeButton.click(function () {
$(this).parent().remove();
});
fieldWrapper.append(fPath);
fieldWrapper.append(fTTL);
fieldWrapper.append(removeButton);
$("#reglas").append(fieldWrapper);
});
$("#cache").each(function () {
$(this).qtip({
content: {
text: $(this).next('.tooltiptext')
}
});
});
});
$('#formsite').on('submit', function (e) {
//prevent the default submithandling
e.preventDefault();
//send the data of 'this' (the matched form) to yourURL
$.post('siteform.php', $(this).serialize());
});
HERE'S MY FULL CODE: http://jsfiddle.net/34rYv/131/
You will want an incrementor. Check out this updated fiddle.
Here is the beginning of the code:
$(document).ready(function() {
var myIncr = 0;
$("#add").click(function() {
myIncr++;
var intId = myIncr;
You can add a class or id to each input field, and then depending on that class or id add the name as
<input type="text" class="something" />
Use this jQuery:
var classval = $('input[type=text]').attr('class'); // get class..
// now add the name as
$(this).attr('name', classval);
You can have as many inputs, they will be added the name depending on their class or id!
So even if the input fields are deleted, you will still have the class attributes in the control!
There's plenty of questions on how to get the value onKeyUp, but I want to pass the id of the form onKeyUp as well.. I tried something like this, but it's telling me getId is not defined.
function getId(x){
$('.not').append(x);
}
var word = 'HELP';
$('.why').html("<form class='questions'><input type='text' id='"+word+"'
name='"+word+"' onkeyup='getId("+word+")'></form> ");
http://jsfiddle.net/evs3A/
Also is putting something like "+variable+" bad practice, because I'm using it quite a lot ;)? Thank u.
Use jQuery to hook up the event and avoid the problem altogether. Try this:
var word = 'HELP';
$('.why').html("<form class='questions'><input type='text' id='" + word + "'
name='" + word + "'></form> ");
$('.questions input').on('keyup', function(e) {
$('.not').append(this.id);
});
Example fiddle
you can change it into this:
$('.why').html("<form class='questions'><input type='text' id='"+word+"'
name='"+word+"'></form> ");
and in jquery:
$(document).ready(function(){
var word = 'HELP';
$(document).on('keyup', '#' + word, function(){
$('.not').append(word); //or $(this).attr('id'); if the id is the argument that you want to pass
});
});
if you want to change a variable to pass you can use data value like this:
<input type='text' id='"+word+"' name='"+word+"' data-something="new_value">
and take it in this mode:
$(document).on('keyup', '#' + word, function(){
$('.not').append(word);
var value = $(this).data('something');
});
Here's a sample without any jQuery.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', mInit, false);
function mInit()
{
byId('myFormId').addEventListener('keyup', onFormKeyUp, false);
byId('myFormId2').addEventListener('keyup', onFormKeyUp, false);
}
// this function was attached to the form in the mInit function.
// as a consequence, 'this' reffers to the form itself.
// this.id should give us the id of the form
function onFormKeyUp(e)
{
alert("Keyup detected in the form with the id: '" + this.id + "'");
}
</script>
<style>
</style>
</head>
<body>
<form id='myFormId'>
<input id='textField1'/>
<br>
<button>Some button</button>
</form>
<form id='myFormId2'>
<input id='textField2'/>
<br>
<button>Some button</button>
</form>
</body>
</html>