no of input fields according to user input - javascript

I have a form that will ask number of input fields from user, and then append inputs to the form. I have developed the function using JavaScript.
The problem is for the first time it will work fine. If I again select another number from the select tag, it will append the number of input fields to the previous inputs.
Example:
If I first select 4 input fields it will show 4 input fields.
If I again select 2 from the select tag it will add another two input
fields.
So altogether 6 input fields. I don't want that. If I select 4 it should be 4. If I again select 2 it should be 2, not 6. Here is my code:
function obj(){
var a=document.getElementById('no_of_obj').value; //select tag value(1 to 6)
var b=document.getElementById('objBlock') //this is the container
var i=0;
while(i<a){
var txt=document.createElement('input');
txt.type="text";
txt.id="obj"+i;
txt.style.height="30px";
b.appendChild(txt);
i++;
}
}

You could clear down the objBlock container before appending the new input elements, using:
b.innerHTML = '';

Try this
function obj(){
var a=document.getElementById('no_of_obj').value;//select tag value(1 to 6)
var b=document.getElementById('objBlock')//this is the container
var i=0;
while(b.children.length < a){
var ct = document.createElement('div');
var txt=document.createElement('input');
txt.type="text";
txt.id="obj"+i;
txt.style.height="30px";
ct.appendChild(txt);
b.appendChild(ct)
}
while(b.children.length > a){
b.removeChild(b.children[b.children.length - 1]);
}
}
Demo: Fiddle
Using jQuery
$(function(){
var $ct = $('#objBlock');
$('#no_of_obj').change(function(){
var count = $(this).val(), counter = count - $ct.children().length;
while(counter-- > 0){
$('<div><input class="input-xlarge"/></div>').appendTo($ct);
}
$ct.children(':gt(' + (count - 1) + ')').remove();
});
})
Demo: Fiddle

Related

jQuery Chose plugin how to remove selected item from drop down

I im using jquery choose plugin that is using two input boxes when page loads...and a need like in this example when i select number 1 in first box that this number is removed from second input box....this works fine...but problem is when i add dynamically input box i can't get item number 1 removed from added dynamic input box.
So question is: how can i remove selected values from input box when selecting other input boxes that is added dynamically and selected items in each select box is not visible in all selected box that exists and is added dynamically?
Here is jsfiddle:
[http://jsfiddle.net/dq97z/640/][1]
And here is picture what i need:
Maybe this will help you out
http://jsfiddle.net/s9r73qjm/
//an array to save selections
var selectedVals = [];
//push to the array when we have selected
selectedVals.push(selectedValue);
//check on the values when building the drop down
$( "#btn_newrow" ).click(function() {
var newList = document.createElement("select");
newList.dataset.placeholder = "Number row 3";
newList.style.width = "350px";
var newListData = new Option("placeholder", "placeholder");
for (var i = 0; i < 6; i++){
if (selectedVals.indexOf(i.toString()) == -1){
//then it hasn't been selected
newListData = new Option(i.toString(), i.toString());
newList.appendChild(newListData);
}
$( ".wrapper" ).append(newList);
}
});

How can I prevent users input to be cloned in the appended input box in javascript

When I insert some thing in the input box of module 1 and click add module button to clone the required elements that I need it clones also the inserted input I've tried to prevent that using event.preventDefault(); but it's still copying the input box with the inserted input from module 1 however, I can't clear it using the clear button that is located in the input box moreover the appended select options doesn't work and when I select an option it doesn't change.
Here is my demo of what's happening:-
http://jsfiddle.net/0ojjt9Lu/6/
and here is my javascript code:
$(document).ready(function(){
$("#Sadd").click(function(event) {
event.preventDefault();
var lastId = $("#modules h1").length;
var $newLabel = $("#module-1-label").clone();
var $newSc = $("#module-1-scredit").clone();
var $newSgrade = $("#module-1-sgrade").clone();
$newLabel.html("<h1>Module " + (lastId+1) + ":</h1>");
$newSc.find("label").attr("for", "Sc"+(lastId+1));
$newSc.find("input").attr("name", "Sc"+(lastId+1)).attr("id", "Sc"+(lastId+1));
$newSgrade.find("label").attr("for", "Sgrade"+(lastId+1));
$newSgrade.find("select").attr("name", "Sgrade"+(lastId+1)).attr("id", "Sgrade"+(lastId+1));
$("#modules").append($newLabel, $newSc, $newSgrade);
});
$("#Sremove").click(function() {
var lastId = $("#modules h1").length;
if(lastId > 5){
var lastLi = $("#modules h1").last().closest("li");
var lastLi2 = lastLi.next("li");
var lastLi3 = lastLi2.next("li");
lastLi.remove();
lastLi2.remove();
lastLi3.remove();
}
});
});
Use .val("") on the new input to clear the data in on the clone
or do $(clone).find('input').val(""); if there is more than one input
In your case with the select box you need to add the following lines
After you declare (or on the same line) the variables
var $newSc = $("#module-1-scredit").clone().find('input').val("");
var $newSgrade = $("#module-1-sgrade").clone().find('option:selected').removeAttr('selected');
$newSgrade.find('option[value="-1"]').attr('selected',true);
Edit: Had to handle the reselection of the select due to default value being "-1" however you may need to look at the cloning of this select element. Perhaps on the page have the blank question hidden and just clone that.

Loop through checkboxes that are not hidden

On a webpage I give the user the option of hiding table elements (which contain checkboxes) like this:
mytable.style.display = 'none'; //the table and the enclosed textbox is hidden
I am now trying to find all of the tables that are not hidden like this:
var frm = document.forms[0];
var arrayDisposals;
var intCount;
var arrayDisposals = new Array();
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].type == "checkbox" && frm.elements[i].name.substr(0, 3) == "Del") {
if ('none' != frm.elements[i].style.display) {
{
arrayDisposals.push(frm.elements[i].id + '|' + frm.elements[i].checked)
}
}
}
The problem is that the second IF statement does not work i.e. all elements are added to the array. How do I only add checkboxes that are not hidden?
If you were looking for a jQuery solution this should suffice. Use .map()
var arrayDisposals = $('input[type="checkbox"][name*="Del"]:visible').map(function(){
return this.id+ "|" + this.checked
}).get();
Use attribute selector to find checkboxes and where the name contains "Del" and :visible to check if it is not hidden.
DEMO

Clone jquery mobile input field with data-clear-btn="true"

Using jquery and jquery mobile I try to make a dynamic form. Input fields are created or removed so that always one empty input field is left.
This is my jquery code to achieve this (try it here:
http://jsfiddle.net/SR864/17/):
$(document).ready(function() {
var total = 1;
// add new field
$("#bar").on("input", ".input", function() {
// add new field
if ($(".input").last().val() != "") {
var newFields = $(this).closest("p").clone();
newFields.find(":input").each(function() {
var name = $(this).attr('name').replace('-' + (total - 1), '-' + total);
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('');
total++;
});
$(this).closest("p").after(newFields);
}
});
$("#bar").on("input", ".input", function() {
// remove empty field
if ($(this).val() == "") {
$(this).closest("p").remove();
}
});
});
I also would like to have "delete-buttons" inside of the input fields to remove the text from the input fields. jquery mobile provides data-clear-btn="true" for that. However, somehow the behavior of data-clear-btn="true" only works for the first input field - the new (cloned) ones don't get the clear button.
Question
How can I have the clear-buttons for the cloned input fields?
Bonus question
What is necessary to have input fields deleted when they are empty after the clear button is pressed?
jQM wraps input fields in a div ui-input-text. You need to clone input itself - not the wrapping div - change its' id, name, val()...etc. Then add it to form and enhance it using .textinput() function.
Moreover, you should wrap code in pagecreate event.
$(document).on("pagecreate", function () {
var counter = 0;
$("#bar").on("input", function (e) {
if ($(e.target).val().length === 1) { /* after 2 characters add a new input */
counter++;
var id = "input-" + counter;
var input = $(e.target).clone().prop({
id: id,
name: id
}).val("");
$(e.target).closest(".ui-input-text").after(input);
$("#" + id).textinput();
}
});
});
Demo
I had a check at the problem. By default the cross button (which is an tag) has a class 'ui-input-clear-hidden' which keeps it hidden till you type. Though you are cloning the element after you start typing, the duplicate element also has this class which keeps it hidden (may be cloning is done before the class 'ui-input-clear-hidden' is removed). So I suggest removing the class 'ui-input-clear-hidden' from your cloned object explicitely as shown below.
$("#bar").on("input", ".input", function() {
// add new field
if ($(".input").last().val() != "") {
var newFields = $(this).closest("p").clone();
newFields.find(":input").each(function() {
var name = $(this).attr('name').replace('-' + (total - 1), '-' + total);
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('');
total++;
});
$(this).closest("p").after(newFields);
}
/* New line Added for Fix*/
newFields.find('a').removeClass('ui-input-clear-hidden');
});

Disable input after submit and count array element

function limitofTags(){
var tags = $('div').find('.tag').map(function(){
return $(this).text();
}).get();
var elem = [];
for (var i = 0; i < tags.length; ++i){
//store array elements
elem.push(tags[i]);
if(elem.length < 2){
$("#tags").prop('disabled',false);
}
else{
$("#tags").prop('disabled',true);
}
}
}
As for html, it is small div with button. When I type tags in input textfield, it will be appended to div area. When tags are more than 2, input textfield will be disabled to prevent more tags from being added. After submit the form, div showed the same number of tags but input textfield won't stay disabled. So how to make input textfield stay disabled if tags are more than 2 in div?
Appreciate the insight or help. I have been searching for online answers but seem not to find what I need the input text disable after submit.
You should probably check the length after the array is populated, and you're creating an elem array that is exactly the same as the tags array you have :
function limitofTags(){
var tags = $('div').find('.tag').map(function(){
return $(this).text();
}).get();
$("#tags").prop('disabled', tags.length >= 2);
}

Categories