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

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');
});

Related

My jquery function is pushing elements to all my arrays

On my website, users can click on some text to open up a Modal. This Modal allows users to choose a bunch of toppings to add to their Pizza.
Through Javascript, I add each selected topping to an array and change the text display to match their selected toppings. This more or less works, but the problem is for some reason, whenever they add a topping, it is added to ALL arrays, not just the item it's selected for. Can someone help me find why this is happening?
// Open Toppings Modal
$(document).ready(function() {
var count = -1
var tplist = []
$(".order").each(function(){
count += 1
tplist.push([])
var listeners = 0
setModal(count, tplist, listeners)
});
function setModal(count, tplist, listeners) {
$("#openModal" + count).click(function(){
console.log("clicked")
$("#toppingModal" + count).modal()
if (listeners == 0) {
listeners += 1
$("input[type='checkbox']").change(function() {
// TODO: Fix Bug
// Adding to all javascript lists
if (this.checked) {
tplist[count].push($(this).val());
console.log(tplist)
}
else {
ele = $(this).val();
pos = $.inArray(ele, tplist[count])
if ( ~pos ) tplist[count].splice(pos, 1);
}
// Change text to list
if (tplist[count].length > 0) {
$("#openModal" + count).text(tplist[count])
}
else {
$("#openModal" + count).text("Select Toppings")
}
})
}
});
};
});
I am suspecting your $("input[type='checkbox']").change(function() {} is called for every model. Try setting count number somewhere when you click select topping and compare inside $("input[type='checkbox']").change(function() {} to prevent adding of toppings in all arrays

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.

js clicking adds color

I have a question. So basically i'm trying to create a js script, when user clicks on a link, it colors the link in different color and then adds the link to an input box, and when the user clicks again on the same link, it changes the color back to original and deletes the text from the input box. The purpose whould be as a search filter, where you can add to search box, predefined keywoards.
$('.tagsSelect a').click(function() {
var clickColor = this.style.color;
if(clickColor = "#F5EBD5"){
var value = $(this).text();
var input = $('#popGirlMenu');
input.val(input.val() + value + ', ');
this.style.color="#f5d47f";
return false;
}
if(clickColor = "#f5d47f") {
var value = $(this).text();
var input = $('#popGirlMenu');
input.val(input.val() - value - ', ');
this.style.color="#F5EBD5";
return false;
}
});
This is my code, it works, bet when the user clicks again on the link, it doesn't change the color back to original and it doesn't remove the text from input box.
p.s sorry for my bad english
Use CSS for your layout, and check the class instead of a color value:
CSS
a { color: blue; }
a.selected { color: red; }
HTML
link a
link b
<input id="txt" type="text" />
JavaScript
$("a").click(function() {
var $this = $(this);
$this.toggleClass("selected");
if ($this.hasClass("selected"))
$("#txt").val($("#txt").val() + $this.text() + ", ");
else
$("#txt").val($("#txt").val().replace($this.text() + ", ", ""));
});
See this jsFiddle
Note to remove a part from a string, you need to replace that part with an empty string. - doesn't work on strings.
Use == or === (comparison) instead of = (setting a variable)

Update text input field dynamically using two select menus with Javascript

I am trying to figure out how to dynamically update a text input field when a user changes the option in one or two HTML select menus. I have included my code below showing how it currently works.
$('tickets').addEvent('change', function() {
if($('tickets').value > 0)
{
var cells = $$('.ticket2');
cells.each(function(cell) { cell.setAttribute('style','display:none;');});
var cells = $$('.ticket3');
cells.each(function(cell) { cell.setAttribute('style','display:none;');});
var sumValue = '$' + (100 * $('tickets').value + 10 * $('fiftytickets').value) + '.00';
$('ordertotal').value = sumValue;
$('ticket1heading').setHTML('Ticket(s)');
} else {
var cells = $$('.ticket2');
cells.each(function(cell) { cell.setAttribute('style','');});
var cells = $$('.ticket3');
cells.each(function(cell) { cell.setAttribute('style','');});
$('ticket2heading').setAttribute('style','text-align:center; font-weight:bold;');
$('ticket3heading').setAttribute('style','text-align:center; font-weight:bold;');
$('ordertotal').value = '$' + 250 + '.00';
$('ticket1heading').setHTML('Ticket 1');
}
});
The tickets select menu correctly affects the ordertotal text input field, but the fiftytickets select menu does not. I need the two to work independently of each other, but when each is changed, to affect the value of the ordertotal text input field.
Any assistance is greatly appreciated.
Thank you.
Mike
as said by JoDev, the select element's object is referenced with $('#tickets') and not just $('tickets').
also, I don't think that there is a value property in jquery for a select element.
you can get the value with the val() function.
Created a little fiddle for you here here
$('#tickets').change(function() {
$('#output').val($(this).val() + " - " + $('#fiftytickets').val());
});
$('#fiftytickets').change(function() {
$('#output').val($('#tickets').val() + " - " + $(this).val());
});

no of input fields according to user input

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

Categories