Creating Multi value fields - javascript

I want to allow users to dynamically create as many input fields as they want within the format that I supply to them.
I need the features below:
There should be a button to add more fields
There should be a button next to each field to delete the field
Is there any method which satisfies my needs?
I've already used the append() method in JavaScript but I was not able to delete the fields using a button next to it.
onclick on a button:
$( '#some_div' ).append( '<input type="text" name="tel[]" class="form-control">' );
I've heard something about grids but could not find anything relevant.

append() will work for adding fields. To subtract fields you could use remove().
One possible method of performing this action is done by wrapping the field and the delete button in a div, making it easy to target the entire group for deletion. jQuery's closest() finds the closest element up the DOM that matches your search, relative to the location you're searching from.
$("#add-field").click(function() {
$("#some_div").append('<div class="input-block"><input type="text" name="tel[]" class="form-control"><input type="button" class="remove-field" value="-"></div>');
});
$(document).on("click", ".remove-field", function() {
$(this).closest(".input-block").remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="add-field" value="+ Add Field">
<div id="some_div"></div>

Related

Target Previous Input Field

I am attempting to target the previous input field of a form element that is in an accordion. I have tried several ways to target the .image-url field but I am having trouble with targeting just this one field within the accordion. This may be a simple task but I cannot get this thing to work. Any help would be greatly appreciated.
HTML
<form>
<input class="image-url" type="text" />
<input class="button" type="button" />
</form>
JS
$('form .button').click(function() {
// do stuff
uploader.on('select', function() {
$(this).prev().val('text to put');
}
}
This is what I have right now and I cannot get it to work.
this within the uploader.on callback probably isn't the button. Remember the button and then use it in the callback:
$('form .button').click(function() {
var btn = $(this);
// do stuff
uploader.on('select', function() {
btn.prev().val('text to put');
}
});
Side note: Whenever I see an event handler hooked up from within another event handler, it raises a flag for me. If the button is clicked twice, you'll end up with two handlers on uploader for the select event. You might want to check whether that's really what you want...
Side note 2: CSS selectors can do more than just ids and classes, you may not need that class="button" on the button. You can select it via form input[type=button] (in your CSS for styling, and in a jQuery $() call and similar to locate it).

problems with jquery Tree Traversal

(1) I've a scenario where there are some checkbox with a "Other" (user typed option) checkbox
(2) When clicking on the checkbox of "Other", a input field will come and cover the "Other" text.
(3) User can type at there and there is an "ok" button beside the checkbox.
(4) When user click the "Ok" button, input field will be gone and user typed text will come at the place of previous "Other" text. At the same time new "Other" fields should come after previous. Also previous "Other" shouldn't expand any more as it's not "Other" anymore(for example, it's now Black).
To make this, I've written jQuery like this:
$('.otherOption input[type="checkbox"]').click(function() {
$(this).closest('.otherOption').find('.box').toggle();
});
$('.ok').click(function() {
var value = $('.optionInput').val();
$('.box').hide();
$('.otherOption p').text(value);
$('.otherOption').removeClass('otherOption');
$(this).closest('.otherOption').append('<div class="block otherOption"><input type="checkbox" /> <p>Other</p><div class="box"><input type="text" value="" placeholder="Provide your option" class="optionInput" /><button class="ok">Ok</button></div></div>');
});
I think, I can write some script correctly. But, as I ain't good at jQuery, I can't write the jquery selector(.closest(),.parents(),.next() etc) that's why, my script is not working. So, please help me to make my script correct. Thanks in advance
My fiddle
Good start. A couple things to make this work the way you want.
You code $('.otherOption').removeClass('otherOption'); removes all instances of the otherOption class which is why your append isn't working.
If you removed the line mentioned above, you're appending the new checkbox inside the wrapper of the other checkbox which I can imagine isn't the desired result. I would imagine you want the new checkbox to come .after() the old otherOption box.
These being said remove this line:
$('.otherOption').removeClass('otherOption');
and change your $(this).closest('.otherOption')... to
$(this)
.closest('.otherOption')
.removeClass('otherOption')
.after('<div class="block otherOption"><input type="checkbox" /> <p>Other</p><div class="box"><input type="text" value="" placeholder="Provide your option" class="optionInput" /><button class="ok">Ok</button></div></div>');
A side note - cause you'll wonder later - your .click() function's won't work more than once. .click() binds to all matching objects on the page load. So any items added dynamically after page load will not work. Look into using jQuery's .on() method. This will ensure you're code works on all matching items no matter when they're added to the DOM.
Edit: One other thing, I noticed that when you repetitively added items, it always added the text from the first box b/c you are not removing the used text boxes. I've added $(this).closest('.box').remove(); to the end of the JS code to fix this issue.
Here's a working fiddle with jQuery's .on() implemented http://jsfiddle.net/a695jk2d/4/
Don't just copy and paste it, understand it.
It might make more sense to simply insert a new structure above your already existing "Other" option. Why replace it's text, and add a whole new 'other' option block? This version will insert a new option above the "Other" option. This way you also only need to bind to the element once as well.
$( '.ok' ).click(function () {
var value = $( '.optionInput' ).val();
$( '.optionInput' ).val('');
$( this ).parent().parent().find( '.box, p' ).toggle();
$( '.otherOption input[type="checkbox"]' ).attr( 'checked', false );
$( '#optionContainer' ).append(
'<div class="block"><input type="checkbox" /> <p>' + value + '</p></div>'
);
});
jsFiddle

Adding inputs on the fly jquery

I was wondering if I could get some help with jquery. This is the html I have now:
http://jsfiddle.net/spadez/9sX6X/4/
<form name="input">
<input id="current" type="text" name="content" placeholder="content">
<input type="submit" value="Add" id="add">
</form>
What I want to do is when the user clicks "add" and as long as the input field isnt empty, I want to do the following:
Change that input field id to "accepted" and remove the add button
next to it and replace it with a remove button
Add an input field below the original one with the id to "current"
with an add button next to it
I want this process to happen every time the add button is clicked so more and more input boxes can spawn under each other. As far as I got was trying to spawn input boxes but even that doesn't work.
function addField(){
$('#add').append('<input type="text" name="myinput" />');
return false;
}
Can anyone please show me how this should be achieved.
I think it isn't a good solution to clone existing elements every time. Instead I would suggest cloning ... well... clones )) The original input and button remain the same, only visually shifted.
Is this behavior needed? - http://jsfiddle.net/skip405/9sX6X/6/
Use before()
$('#add').before('<input type="text" name="myinput" />');
since you need to append the new input just before your submit button (and not into it, which is not possible here, since it's an input element)
A working example http://jsfiddle.net/steelywing/9sX6X/12/
$('form').on('click', '.add', function () {
var row = $(this).closest('div'),
new_row = row.clone();
row.find('input:text').addClass('accepted');
row.find('.add')
.removeClass('add')
.addClass('remove')
.val('Remove');
new_row.find('input:text').val('');
row.after(new_row);
}).on('click', '.remove', function () {
$(this).closest('div').remove();
});

Modify underlying form.reset() values

I'm using $('form-selector').get(0).reset() to reset form values to their original page load state.
After editing, the form will submit via $.ajax() and I'll have new "default" values on our server. The form element will still exist in the dom, and the user can submit again to update. I'd like the "default" (reset values) to reflect what's on our server (ignoring any other external updates). Is it possible to update the underlying values that form.reset() will change each form element to without a page refresh?
Cross-browser support would be nice, but since this is an internal app, Google Chrome only is sufficient.
HTML
<form>
<input type="text" value="foo" name="bar" />
<input type="submit" value="Submit" />
<Input type="reset" value="Reset" />
</form>
JAVASCRIPT
$(function(){
$('form').submit(function() {
// Omitting code that sends form values to the server
// TODO: update underlying form.reset()
// values to what's currently in each
// form element.
return false;
});
});
UPDATE
Ack! I failed to mention that I'm looking for something to handle all form element types.
i.e. input[type=text], input[type=radio], input[type=checkbox], select, textarea.
Would be especially awesome if it can handle HTML5 form elements as well...
i.e. input[type=date], input[type=number], input[email], input[url], input[type=range], input[type=color], etc.
Sorry for the confusion.
If you change attributes of the form elements directly, rather than using the .val() method, the new values will be reflected on a form reset. You'll need to treat text fields differently from radio buttons, checkboxes, etc.
$('input').attr('value', function() { return this.value });
$('textarea').prop('innerHTML', function() { return this.value });
$(':checked').attr('checked', 'checked');
$(':selected').attr('selected', 'selected');
$(':not(:checked)').removeAttr('checked');
$(':not(:selected)').removeAttr('selected');
Something like this:
$("#foo").prop("defaultValue", "bar");
As David Budiac mentioned in his comment, this doesn't work for select elements. Select elements have a separate property named defaultSelected.
More about the defaultValue property
I realize that these links go to Microsoft's site but they seem to work in pretty much all mainstream browsers.
Javascript does not know what the reset values are, so you'll have to define them either on page load or make hidden field(s) with the reset values. Then when you call reset, set them.
Let's say you have hidden fields for each field you have in your form, like text boxes (you can do similar ones for dropdowns and radio/select)
If you have 2 text fields (txtfield1 and txtfield2), you would also have hidden fields for them (called txtfield1-hdn and txtfield2-hdn respectively).
$('form-selector').get(0).reset(function() {
$('form-selector').find('input').each(function(){
$(this).val($($(this).attr('id') + '-hdn').val());
});
});
of if you have default values in the text field html then you can just do this:
<input id="Text1" type="text" value="myValue" />
$('form-selector').get(0).reset(function() {
$('form-selector').find('input').each(function(){
$(this).val($(this).attr('value'));
});
});

Selecting the correct input field using jquery

I'm trying to select the id's of dynamic input fields in my code. When clicking a button, the form will create a form field like this:
<td><input type="text" id="field_a_1"></td>
<td><input type="text" id="field_b_1"></td>
<td><input type="text" id="field_c_1"></td>
When I click on the button again I get this:
<td><input type="text" id="field_a_2"></td>
<td><input type="text" id="field_b_2"></td>
<td><input type="text" id="field_c_2"></td>
What I want to do is select only the field id that I need to pull the value from that particular input and pass it to a variable like this:
var example = $(":input:eq(0)").val();
I know that by adding the :eq(0) after the :input selector it will only grab the id for field_a_1, so how do I set it up so that I can pull just the field that I need to assign it to a variable?
That is what the ID is for. So you can single out a particular element.
$('#field_b_2').val(); // Will return the element with that ID.
The # indicates that you are looking for an element with an ID, as opposed to . which would look for an element (or elements) with a class:
$('.someClass').val(); // Will return elements with that class
Please remember that IDs may not be shared among elements. Only one element may have a particular ID.
Classes, on the other hand, can be shared among as many elements as you need.
If you want only the id of the element you should do:
var example = $(":input:eq(0)").attr("id");
And then you can access the field again later with:
$("#" + example).show(); //or whatever you want to do
your Input Ids keep changing like :
When you click first time it will All: field_a_1 then , field_a_2, etc.
you simply using this to getting the correct values.
$('input[id^=field_]').each(function(){
alert($(this).val());
});

Categories