Cloning div and incrementing - jquery-mobile

I am atempting to clone a div (multiple times) and add increments so I can parse the results into a database using XML. I only want to clone the form section not the data entered. The Div I am cloning has 3 selects and 2 radios (all of which when added need to be empty).
HTML
<div id="Template1" class="template">
<div class="_100">
<div class="_25"> <fieldset>
<label class="label_analysis" for="analysis">Analyte:</label>
<select class="select_analyte" name="analysis" id="analysis">
<option value="">Select</option>
<option value="TN">TN</option>
<option value="TP,NO2+3">TP,NO2+3</option>
</select> </fieldset></div>
<div data-role="controlgroup" class="_13">
<label><input type="checkbox" data-mini="true" name="Filtered" id="Filtered" value="True">
0.45u Filtered</label>
<label><input type="checkbox" data-mini="true" name="Dup" id="Dup" value="True">
Field Dup</label></div>
<div class="_25"><fieldset>
<label class="label_preserve" for="preserve">Preserved</label>
<select class="select_preserve" name="preserve" id="preserve">
<option value="">Select</option>
<option value="HNO3">HNO₃</option>
<option value="H2SO4">H₂SO₄</option>
</select></fieldset></div>
<div class="_20"> <fieldset>
<label class="label_cool" for="cool">Cooled</label>
<select class="select_cool" name="cool" id="cool">
<option value="">Select</option>
<option value="Ice">Ice</option>
<option value="Frozen">Frozen</option>
<option value="None">None</option>
</select>
</fieldset></div>
<div class="_13">
Add Analyte
Remove</div>
</div>
</div>
<div id="place" class="place"></div>
I have tried two different scripts
This script works as I want to hide the remove button on the original div and only have it appear on the cloned but it doesn't increment.
(function($){
var Template = $('.Template');
var count = 0;
$('.removeNew').hide().on('click', function(e) {
e.preventDefault();
$(this).closest('.Template').remove();
});
$('a.showNew').on('click', function(e) {
e.preventDefault();
var clone = Template.clone(true, true).insertAfter("#place").find('.removeNew').show().end();
});
})(jQuery);
and this one which increments but doesn't hide the remove button
$('#showNew').click(function() {
var num = $('.template').length,
newNum = new Number(num + 1),
newElem = $('#Template' + num).clone(true, true).attr('id', 'Template' + newNum).appendTo('#place');
newElem.find('.analysis').attr('id', 'ID' + newNum + '_analysis').attr('name', 'ID' + newNum + '_analysis').val();
newElem.find('.preserve').attr('id', 'ID' + newNum + '_preserve').attr('name', 'ID' + newNum + '_preserve').val();
newElem.find('.cool').attr('id', 'ID' + newNum + '_cool').attr('name', 'ID' + newNum + '_cool').val();
$('#Template'+ num).after(newElem);
});
})
I am wondering if there is some way to combine them...
I am also having issues as no matter what I seem to try the original div becomes the clone, complete with remove button, while what should be the original div can be changed.

I believe the simplest approach is to have an original copy of the template hidden and base all clones off of that. This fiddle demonstrates this approach.
(function ($) {
var Template = $('#Template');
var count = 0;
var nextId = 0;
Template.find('.removeNew').on('click', function (e) {
e.preventDefault();
$(this).closest('.template').remove();
count--;
});
function cloneTemplate(removable) {
var clone = Template.clone(true, true);
clone.attr('id', clone.attr('id') + nextId);
clone.find('label[for]').each(function( index ) {
var elem = $(this);
elem.attr('for', elem.attr('for') + nextId);
});
clone.find('select, input').each(function( index ) {
var elem = $(this);
elem.attr('id', elem.attr('id') + nextId);
elem.attr('name', elem.attr('name') + nextId);
});
if (!removable) {
clone.find('.removeNew').remove();
}
clone.insertBefore("#addNew").removeClass('hide');
count++;
nextId++;
}
// Create First Analyte and delete the remove button.
cloneTemplate(false);
$('a.showNew').on('click', function (e) {
e.preventDefault();
cloneTemplate(true);
return false;
});
})(jQuery);
It didn't make sense to have the Add New button inside the template so I moved it outside. All new clones are added before the Add New button.
You should notice in the script above that the first element is created by cloning the Template. Then new elements are created calling the same clone function when the Add New button is clicked.
Note: This solution does not include updating element id or name attributes. Something that you almost certainly want to do.

Related

jQuery Mobile Navigate Between Pages using Form

I have a form using select values, I'd like to make each option works as a link. How can I do it?
<form>
<label for="direction">Select Direction:</label>
<select name="dir" id="dir">
<option value="1">N</option>
<option value="2"><a href="#page3">S</option>
</select>
</fieldset>
<input type="submit" data-inline="true" value="Confirm">
</form>
Listen to submit event to retrieve select value and then change page.
Remove anchor tag from option, and put page ID in value value="#pageID".
$(document).on("pagecreate", "#pageID", function () {
$("#formID").on("submit", function (e) {
e.preventDefault();
var page = $("#selectID").val();
$.mobile.pageContainer.pagecontainer("change", page);
});
});
Demo

jQuery mobile clone

I am trying to get jQuery-mobile to clone a div like I get it to do on jsfiddle.
head
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<link rel="stylesheet" type="text/css" href="form.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="jquery.maskedinput.min.js" type="text/javascript"></script>
<script type="text/javascript" src="json2.min.js"></script>
<!--[if lt IE 9]>
<script type="text/javascript" src="flashcanvas.js"></script>
<![endif]-->
<script type="text/javascript" src="CreateXMLScript.js"></script>
<script>
$(document).bind('mobileinit', function() {
$.mobile.page.prototype.options.addBackBtn= true;
$.mobile.page.prototype.options.backBtnText="Back";
$.mobile.page.prototype.options.backBtnIcon="arrow-l";
$.mobile.selectmenu.prototype.options.nativeMenu = false;
$.mobile.page.prototype.options.keepNative = ".native";
$.mobile.keepNative=".native";
})
</script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
HTML
<div id="Template" class="template hide">
<div class="_100">
<div class="_25">
<fieldset>
<label class="label_analysis" for="analysis">Analyte:</label>
<select class="select_analyte" name="analysis" id="analysis">
<option value="">Select</option>
<option value="TN">TN</option>
<option value="TP,NO2+3">TP,NO2+3</option>
<option value="TP,NO2+3,NH3+4">TP,NO2+3,NH3+4</option>
<option value="DO">Dissolved Orthophosphate</option>
<option value="TR">TR Metals, Hardness</option>
<option value="FF">Dissolved Aluminum (FF)</option>
<option value="ULL">TR Metals (ULL Hg)</option>
<option value="TSS">TSS</option>
<option value="TSS/TDS">TSS/TDS</option>
<option value="DM">Dissolved Metals (FF)</option>
<option value="TOC">TOC</option>
<option value="ABF">Anions, Bromide, Fluoride</option>
<option value="CH">Cations, Hardness</option>
</select>
</fieldset>
</div>
<div data-role="controlgroup" class="_13">
<label><input type="checkbox" data-mini="true" name="Filtered" id="Filtered" value="True">0.45u Filtered</label>
<label><input type="checkbox" data-mini="true" name="Dup" id="Dup" value="True">Field Dup</label>
</div>
<div class="_25">
<fieldset>
<label class="label_preserve" for="preserve">Preserved</label>
<select class="select_preserve" name="preserve" id="preserve">
<option value="">Select</option>
<option value="HNO3">HNO₃</option>
<option value="H2SO4">H₂SO₄</option>
<option value="H3PO4">H₃PO₄</option>
<option value="HCL">HCL</option>
<option value="None1">None</option>
</select>
</fieldset>
</div>
<div class="_20">
<fieldset>
<label class="label_cool" for="cool">Cooled</label>
<select class="select_cool" name="cool" id="cool">
<option value="">Select</option>
<option value="Ice">Ice</option>
<option value="Frozen">Frozen</option>
<option value="None">None</option>
</select>
</fieldset>
</div>
<div class="_13">
Remove
</div>
</div>
</div>
<div id="addNew">
ADD ANALYTE
</div>
Script
<script>
$(document).ready(function() {
(function ($) {
var Template = $('#Template');
var count = 0;
var nextId = 0;
Template.find('.removeNew').on('click', function (e) {
e.preventDefault();
$(this).closest('.template').remove();
count--;
});
function cloneTemplate(removable) {
var clone = Template.clone(true, true);
clone.attr('id', clone.attr('id') + nextId);
clone.find('label[for]').each(function( index ) {
var elem = $(this);
elem.attr('for', elem.attr('for') + nextId);
});
clone.find('select, input').each(function( index ) {
var elem = $(this);
elem.attr('id', elem.attr('id') + nextId);
elem.attr('name', elem.attr('name') + nextId);
});
if (!removable) {
clone.find('.removeNew').remove();
}
clone.insertBefore("#addNew").removeClass('hide');
count++;
nextId++;
}
// Create First Analyte and delete the remove button.
cloneTemplate(false);
$('a.showNew').on('click', function (e) {
e.preventDefault();
cloneTemplate(true);
return false;
});
})(jQuery)
});
</script>
I have received tons of help with jQuery but no matter what I do, it just won't work in jQuery-mobile. Either it clones upside down (the 1st item becomes last and all fields are populated) or the new fields on the new div won't let me populate them (the current issue).
I didn't create a Fiddle as everything I have tried works in the fiddle, just not in Mobile.
I checked the source of your pages from the link you provided, im not sure exactly what you are trying to achieve as you have a Complex Form. However, place this amended code i made below just before the </body> tag of your page and remove the other script part you have at the moment. Make sure you do a backup of your JQM APP before just incase you need to Undo these changes i am providing.
I also noticed a few $(document).ready(function() { in your pages, these are not needed so remove them. Just a bare bones click functions are ok. You can consolidate all these under one <script> ///// </script>. Where you place your functions is important, as some need to be in the <head> some in the <body> and some after the </body> or </html> tags
<script>
var Template = $('#Template');
var count = 0;
var nextId = 0;
Template.find('.removeNew').on('click', function (e) {
e.preventDefault();
$(this).closest('.template').remove();
count--;
});
function cloneTemplate(removable) {
var clone = Template.clone(true, true);
clone.attr('id', clone.attr('id') + nextId);
clone.find('label[for]').each(function( index ) {
var elem = $(this);
elem.attr('for', elem.attr('for') + nextId);
});
clone.find('select, input').each(function( index ) {
var elem = $(this);
elem.attr('id', elem.attr('id') + nextId);
elem.attr('name', elem.attr('name') + nextId);
});
if (!removable) {
clone.find('.removeNew').remove();
}
clone.insertBefore("#addNew").removeClass('hide');
count++;
nextId++;
}
// Create First Analyte and delete the remove button.
cloneTemplate(false);
$('a.showNew').on('click', function (e) {
e.preventDefault();
cloneTemplate(true);
return false;
});
</script>

resize button option box etc.ajax implement on internal pages

ive been studying this link but i cant figure out how he resize the option box and i want to know how to resize option box text box buttons etc. in jquery mobile but i cant find a way to resize them i also want to know if it is possible to impelement ajax on a jquery mobile that uses internal pages?and also how can you set the distance between label and textbox?here is the code of the link
http://jsfiddle.net/HwFFU/1/
<div data-role="page">
<div data-role="header">
<h1>My Title</h1>
</div><!-- /header -->
<div data-role="content">
<form method="post" action="processForm.php">
<li data-role="fieldcontain">
<label for="children" class="select">Number of Kids</label>
<select name="children" id="children" data-mini="true">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</li>
<div id="kidsFields"></div>
</form>
</div><!-- /content -->
</div>
var html = '';
$('#children').on('change', function() {
children = $(this).val();
html = '';
for (var i = 0; i < children; i++) {
html += '<label>Name</label><input type="text" id="textName' + i + '" name="child' + i + 'Name" /><label>Age</label><input type="text" name="child' + i + 'Age" id="textAge' + i + '" />';
}
$('#kidsFields').html(html);
$('#kidsFields').append('<input type="submit" value="Submit" />');
$('.ui-page').trigger('create');
});
I have updated your fiddle: http://jsfiddle.net/ezanker/HwFFU/20/ Here each Name/Age input field pair is on a single line with the inputs resized and the distance between label and input set.
When inserting the form elements, you can surround them with a div set to a data-role of fieldcontain (this also automatically stacks the elements on narrow screens):
for (var i = 0; i < children; i++) {
html += '<div data-role="fieldcontain"><label>Name</label><input type="text" id="textName' + i + '" name="child' + i + 'Name" /><label>Age</label><input type="text" name="child' + i + 'Age" id="textAge' + i + '" /></div>';
}
Then use CSS to set input field size and distance between label and input e.g.
#kidsFields .ui-input-text{
width: 80px;
margin: 1em;
}
And, yes you can use AJAX with jQM internal pages. Perhaps you should create a separate and more specific question about that...

Dynamically populating checkbox from database using ajax

I am new with JQuery. (I want to do it using AJAX, JQuery, PHP)
I am trying to dynamically populate a list of checkboxes from the database.
What I have is a drop down. Based on the selected option I want to query the database, and depending on the recordset I want to dynamically display the checkboxes.
Any suggestions
<script>
$(function(){
$("#softwareapp").change(function(){
if($(this).val() > 0){
var app_id = $('#softwareapp').val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>ajaxcalls/get_softwareappversions/"+app_id,
data:{savid = $(this).val()},
success: function(data){
var _table = $("<table></table>");
for(var i = 0; i< data.length; i++){
$("<tr></tr>").append($("<td></td>").html("<label><input type='checkbox' value='data[i]' name='softappver[]'/>" + data[i] + "</label>")).appendTo(_table);
}
$("#displayappversions").html("").append(_table);
}
});
}
});
})
For some reason this has stoped working. I am trying to get rid fo the table stuff.
and following is my HTML:
<select name="softwareapp" id="softwareapp">
<option value="0" selected="selected">Please select</option>
<option value="1">SAP</option>
<option value="2">SAGE</option>
<option value="3">SWIFT</option>
</select>
<div class="form-row">
<p class="form-label">Application Version</p>
<div class="form-item" id="displayappversions">
<!--- VERSIONS ARE SUPPOSE TO COME HERE--->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#vendor").change(function(){
if($(this).val() > 0){
$("#displayappversions").load("<?php echo base_url(); ?>ajaxcalls/get_softwareappversions/" + $(this).val());
}
});
});
My ajax call is returning HTML that makes the list of chcek boxes.

jquery custom events attached to .show and .hide

I'm exploring the potential of jquery to satisfy some of our UI requirements, and am experiencing some curious behaviour. I'm very new to jQuery, and I'm trying to implement a basic pub-sub type of pattern that's hooked into the show & hide functions.
Despite the custom event mechanism looking perfectly simple on the surface, it isn't behaving as I expect. I can't see my syntactical mistake, so I must be misunderstanding the way these custom events are intended to work.
When I execute this code, Here's what I think should happen.
Initially (after doc.Ready) the question2 element should be hidden.
When I click on the 'Vermont' radio button, question 2 should be made visible followed by one alert box indicating that 'question2 has been made visible'.
When I click on another radio button, question 2 should be hidden followed by one alert box indicating that question 2 has been made hidden.
What is actually happening is that I get numerous alert boxes when making question 2 visible, and none when I hide it?
Please help me understand why it's doing this.
Here is the script:
<script type="text/javascript">
function processRadioButtonASD() {
var isChecked = ($("input[name=question1]:checked").val() == "question1.Vermont");
if (isChecked == true) {
$("[data-uniquename=question2]").show(250);
} else {
$("[data-uniquename=question2]").hide(250);
}
}
function detectVisibilityChange(uniqueName) {
$("[data-uniquename=" + uniqueName + "]").bind("madeVisible", function () {
alert($(this).attr("data-uniquename") + " was made visible");
});
$("[data-uniquename=" + uniqueName + "]").bind("madeHidden", function () {
alert($(this).attr("data-uniquename") + " was made hidden");
});
}
$(function () {
$.each(["show", "hide"], function () {
var _oldFn = $.fn[this];
$.fn[this] = function () {
var wasVisible = $(this).is(':visible');
var result = _oldFn.apply(this, arguments);
var isVisible = $(this).is(':visible');
if ((isVisible == true) && (wasVisible == false)) {
$(this).triggerHandler("madeVisible");
} else if ((isVisible == false) && (wasVisible == true)) {
$(this).triggerHandler("madeHidden");
}
return result;
}
});
});
$(document).ready(function () {
processRadioButtonASD();
detectVisibilityChange("question2");
$("input[name='question1']").change(function () { processRadioButtonASD(); });
});
</script>
Here is the html:
<div id="content">
<div id="radioButtonASD" class="example">
<h2>radio button visibility trigger</h2>
<div data-uniquename="question1" class="question">
<label for="question1">
Question 1) (select Vermont to show Question2)
</label>
<br />
<label data-uniquename="question1.Maine">
<input name="question1" data-uniquename="question1.Maine" type="radio" value="me" />Maine</label><br />
<label data-uniquename="question1.Vermont">
<input name="question1" data-uniquename="question1.Vermont" type="radio" value="question1.Vermont" />Vermont</label><br />
<label data-uniquename="question1.NewHampshire">
<input name="question1" data-uniquename="question1.NewHampshire" type="radio" value="question1.NewHampshire" />New
Hampshire</label><br />
<label data-uniquename="question1.Conneticut">
<input name="question1" data-uniquename="question1.Conneticut" type="radio" value="question1.Conneticut" />Conneticut</label><br />
<label data-uniquename="question1.Massachusetts">
<input name="question1" data-uniquename="question1.Massachusetts" type="radio" value="question1.Massachusetts" />Massachusetts
</label>
</div>
<br />
<div data-uniquename="question2" class="question">
<label>
Question 2)
</label>
<br />
<select>
<option data-uniquename="question2.honda" value="honda">Honda</option>
<option data-uniquename="question2.volvo" value="volvo">Volvo</option>
<option data-uniquename="question2.saab" value="saab">Saab</option>
<option data-uniquename="question2.mercedes" value="mercedes">Mercedes</option>
<option data-uniquename="question2.audi" value="audi">Audi</option>
</select>
</div>
</div>
</div>
Thanks for looking.
I came up with an alternative way.
$.each(["show", "hide"], function() {
var effect = $.fn[this];
$.fn[this] = function(duration, move, callback) {
// Match the arguments
var speed = duration;
var easing = callback && move || move && !jQuery.isFunction( move ) && move;
var fn = callback || !callback && move || jQuery.isFunction( duration ) && duration;
// Wrap the callback function
var wrapped = fn;
var wasVisible = $(this).is(':visible');
fn = function(){
var isVisible = $(this).is(':visible');
$.proxy(wrapped, this);
if ((isVisible == true) && (wasVisible == false)) {
$(this).triggerHandler("madeVisible");
} else if ((isVisible == false) && (wasVisible == true)) {
$(this).triggerHandler("madeHidden");
}
};
// Run the effect with the wrapped callback
return effect.call(this, speed, easing, fn);
};
});
The idea is make use of the callback function. From there you can refactor and clean the code.
Take a look at a working example.

Resources