Dynamically added a field in different forms using Jquery - javascript

I'd like to have a field that doesn't show at first, but if the user decided to input to it, then it will appear in the form.
I can use Jquery and do something like
$('input[example]')
.bind('click', function() {
$('#clickfield')
.append('<input id="new_field" name="MODEL[new_field]" size="30" type="text">');
However, I'd like to add this field in several different forms for different models.
Since the model name is in the field, how would I write the Jquery script to be modular so I can use the same script for all my forms?

One solution is to make a function with the names you want as input parameters:
addInput(form, id, modelName) {
$(form).append(
'<input id="'+id+'" name="'+modelName+'['+id+']" size="30" type="text">'
);
}
Where form would be the selector of the field ('#clickfield' in the example case), id would be the id of the new input field, and modelName would be the name of the model you mentioned.
Other solution, assuming 'input[example]' selects some button or clickable area that triggers the event of showing the field; and '#clickfield' is some div or span or some area where you will show your field, is to load these hidden fields from the server, styled as display:none, with a mnemonic class, so you could do something like define a function:
showField(clickable, class) {
$(clickable).click(
function(){
$(class).show();
}
);
}
and then:
$(document).ready(
showField('input[example1]', '.class1');
showField('input[example2]', '.class2');
showField('input[example3]', '.class3');
// .
// .
// .
// One line for every clickable area that triggers
// the event of showing a field, and the class of the
// field to show
);
this way you could add some user friendly features like fading the field in with the fadeIn() Jquery function (instead of show()), or any other animation on appearing.
Hope you could use it! good luck!

Related

how to validate p,li,div elements text

I want to validate the p,li,div element texts. examples, I have an p tag with the class name "date". then the user can insert only a date.if they inserting text I want to display alert to the user in CKEDITOR.
Is it possible to in ckeditor without using any input fields<p class="date"></p>
<p class="date">31/07/2018</p>
<p class="date">a</p> I need to display error or alert.
how can i do without onchange events. is there have any default funtionality
You can get elements by class in jQuery. Then the validation process is straightforward
function isDate(value) {
var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/
return value.match(dateReg)
}
$("p.date").map(function() {
if(!isDate(this.innerHTML)) {
//alert("...");
}
});
As for the part - when to run these validation checks, you can call them on DOM updates like, insertion, deletion etc in the application layer.

Working With Dynamically Created Inputs

I have a dynamic form that you can add elements. Like, you type a name, and then if you have to write a new name, you click on 'Add Name', and another textbox appears.
Their names are names[]. I can process those inputs with PHP on the server-side. However, I want to make a calculation with those inputs, like writing all of them on the page as the user types.
However, because those inputs, those textboxes are created dynamically, Javascript only selects the first textbox with the name name[].
Let me make it clear. This way it'll be better. I got a textbox. I input age in there. If I want to enter a new age, I click 'Add Age' button, and a new input box pops out. I write the new age value. And as I type, on a 3rd textbox, the average of those age values get printed. But because of those input boxes, with names ages[] are created on the execution time (not the compile time, I'm not sure these are the appropriate words for those. Probably not, because nothing is compiling? - or is it?), I can't process them.
What must I do to solve this problem?
I used both
$('input[name=ages\\[\\]]').change(function(){
console.log('1');
});
and
$('input[name=ages\\[\\]]').on('input', function() {
console.log('2');
});
but it didn't work.
Thanks in advance.
There's no need to escape the square brackets (though you should enclose the whole field name in double quotes). This works for me:
$('input[name="names[]"]').on('change', function(){
console.log($(this).val());
});
Here's a jsfiddle demonstrating: http://jsfiddle.net/t7J5t/
Your problem is actually probably related to the fact that you're adding the fields dynamically. The way you're using your selector will only work on the fields that already exist. Fields that are added after that selector will not be picked up. What you want to do, then, is put the selector inside the .on, like this:
$('.container').on('change', 'input[name="names[]"]', function(){
console.log($(this).val());
});
This will bind the listener to the container, not the fields (just make sure your fields get added inside of the container; you can call it whatever you want).
Incidentally, there's no reason you have to restrict yourself from using the name attribute of fields when using jQuery selectors. For example, you could use a class:
<div class="container">
<input class="age" name="ages[]">
<input class="age" name="ages[]">
<!-- ... as many more as needed, added dynamically is OK ... -->
</div>
<script>
$(document).ready(function(){
$('.container').on('change', 'input.age', function(){
console.log($(this).val());
});
});
</script>
Here's a sample of it in action, where you can dynamically add fields, and it calculates the average:
http://jsfiddle.net/t7J5t/1/
Try to use:
$(document).on('change', 'input[name=ages\\[\\]]', function() {
console.log('2');
});

Hide the input field div class using javascript

I have a payment form,in which when I click on the internet banking ,all the input field be disabled and instead show some images. this is the fiddle upto which i have done http://jsfiddle.net/f8Fd3/4/ No where I cant hide the input text field using their class id.
this is the js
function cc()
{
$('#cards.credit-card').removeClass("visa mastercard").addClass("visa");
}
function dc()
{
$('#cards.credit-card').removeClass("visa mastercard").addClass("mastercard");
}
function ib()
{
}
please check the fiddle to get a clear picture
It is because, by default, when 'button' tag inside a 'form' is clicked, 'form' will be submitted.
It's not redirecting for the other two because there's a HTML5 form validation that prevents the form from being submitted. (that's why you will see an error message when you click Visa/Mastercard)
if you insist on binding events in the dom...you can pass an event object to the handler:
<button onclick="javascript:ib(event)" class="btn btn-1 btn-1c">Internet Banking</button>
and in your function:
function ib(event) {
event.preventDefault();
}
you may wanna do the same to the other two handlers as well.
so the default submit action will be prevented.
and to disable all the text fields:
$('#cards input[type=text]').prop('disabled', true);
to hide them:
$('#cards input[type=text]').hide();
EDIT
by the way. you don't have to use selectors like $('#cards.credit-card'), 'id' should be unique in the DOM, just by using $('#cards') you will get the same element.
The syntax class="class=tokenex_data full gr-input" is incorrect.
Instead use, class="tokenex_data full gr-input"
Then use :
`function ib()
{
$(".tokenex_data").hide();
$(".monthgr-input").hide();
}
`
You want to select all input & select elements and set their property disabled to true:
$('#cards input, #cards select').prop('disabled', true);
Fiddle

Dynamically created inputs with if else checkbox and multiple field validation

When the user clicks add more options, a from is created with javascript document.getElementById('addmore').innerHTML... It works great to display the form multiple times. I added a unique number each time to create unique IDs for each of the fields for submission. I have a checkbox that, if checked, needs to display another fields to get filled out:
document.getElementById('addmore').innerHTML += '<p><div class="required">*Type of Folder</div><label for="it09" class="hidelabel">Content Drive</label><input name="request['+fields+'][Type of Folder:]" id="cbpathCDB'+fields+'" type="checkbox" value="Content Drive" class="required" /><strong>Content Drive</strong> (A: drive)<br /><div id="pathCDB'+fields+'"><label for="newpathCDB"><span class="req">*Path to Content Drive Folder</span></label><input name="request['+fields+'][Path to Content Drive Folder:]" type="text" id="npcdb'+fields+'" size="50" class="required"/><br /><small>Path of folder to be created on Content Drive (A: drive)<br><em>(example: A:\drivefolder</em></small><br /></div></p>';
I have tried multiple ways (jquery included) of getting the next div, pathCDB+fields, to show when the checkbox is checked. It works fine without the +fields in there... see http://jsfiddle.net/kuVzV/4/ however, when I add the fields it fails to show/hide with the checkbox.
When the form is created though, the div doesn't show at first, just like it shouldn't... so I know the ID is correct. According to Firebug it is showing the correct ID with the field showing the correct # that is create...
I am at a loss right now.
Any suggestions on how to show/hide this div if the checkbox is checked for multiple inputs created dynamically?
Try checking out jQuery .show() and Jquery .hide(). I believe this is what you are looking for.
$(document).ready(function(){
$("#cbpathCDB1").on('click', $("#cbpathCDB1 input[type=checkbox]").is(":checked"), someFunction);
});
function someFunction(event){
if (event.target.checked){
$("#pathCDB1").hide('slow');
}
else{
$("#pathCDB1").show('slow');
}
}​
jsfiddle http://jsfiddle.net/FERMIS/7ThtT/6/ Here is an example with multiple fields.

browser auto fill event

I am doing some website where I have a login form. I know people can save their usernames and passwords on these in their web browsers.
I need to show / hide a label (<label></label>). if the field is empty then the label has to appear, if there is any value in the field then the label has to hide,
but this doesn't work with the browser autocomplete, is there anyway I can track this?
I tried with:
jQuery.change();
but that doesn't work.
Is there anything I can do about this rather than turning autocomplete off?
The norm here is to use the placeholder attribute on the relevant input element:
<input type="text" placeholder="username">
username will be displayed within the input when there's no text, and hidden otherwise. If you're using this, then you should probably also use something like Modernizr to detect support and create a normal text label otherwise.
You have to manually trigger the change event:
$("#username")
.change(function () {
// do stuff on change (check for default)
})
.trigger("change");
or use some watermark library if you only want to toggle default text (or the placeholder attribute with Modernizr as aviraldg recommends).
This is very simple.
I use this for my site's text fields.
This coding is in Javascript text.
create a <form> with name and id = "comform" (you can change this later; just for reference).
create an <input type = "text" with name and id = "Message" (you can change this later; just for reference).
create a <div> with id = "ifsend" (you can change this later; just for reference).
Also create a variable to store the length in. var numbering (you can change this later; just for reference).
function counter() {
var numbering;
numbering = document.forms["comform"]["Message"].value.length;
if (numbering == 0) {
label();
}
if (numbering != 0) {
document.getElementById('ifsend').innerHTML="";
}
}
function label() {
document.getElementById('ifsend').innerHTML="Your form value is empty";
}

Categories

Resources