I'm creating a duplicate-able div's containing check box's, at the moment on the original set of inputs, the check boxes act like radio buttons, but when duplicated it still only works on the first not the second.
Also on submit it only returns one value for the original form in the console, but no value for any duplicates.
Any help greatly appreciated.
JS Fiddle: http://jsfiddle.net/dawidvdh/EEd7c/
jQuery:
//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking
//General Variables
var relation_input_groups = ["relation-group-1"];
//General Variables
//Generate variables
var relation_fields=[0];
var relation_input ="<label>Spouse</label>"+
"<input type='checkbox' value='spouse' class='relationship' name='relationship' />" +
"<label>own child</label>"+
"<input type='checkbox' value='ownchild' class='relationship' name='relationship' />" +
"<label>adopted</label>"+
"<input type='checkbox' value='adopted' class='relationship' name='relationship' />" +
"<label>stepchild</label>"+
"<input type='checkbox' value='stepchild' class='relationship' name='relationship' />" +
"<label>parent</label>"+
"<input type='checkbox' value='parent' class='relationship' name='relationship' />" +
"<label>inlaw</label>"+
"<input type='checkbox' value='inlaw' class='relationship' name='relationship' />" +
"<label>brother</label>"+
"<input type='checkbox' value='brother' class='relationship' name='relationship' />" +
"<label>other</label>"+
"<input type='checkbox' value='other' class='relationship' name='relationship' />";
//Generate variables
jQuery(document).ready(function(e)
{
//populate jquery generated fields
jQuery(relation_fields).each(function()
{
jQuery(relation_input).appendTo('#relation-group-1');
});
//populate jquery generated fields
//Cloning Function
jQuery('#clone').click(function()
{
clone_dependant();
});
function clone_dependant()
{
// Store the value of the previous Id to insert the cloned div..
var oldId = g_counter;
g_counter++;
currentdep ='dependant-'+g_counter;
// Clone the Dependant Div and set a new id
var $clonedDiv = jQuery('#dependant-1').clone(false).attr('id', 'dependant-'+g_counter);
var relation_newDiv = 'relation-group-'+ g_counter;
// Find div's inside the cloned object and set a new id's
$clonedDiv.find('#relation-group-1').attr('id',"relation-group-" + g_counter );
// You don't need to Loop thru the inputs to set the value
$clonedDiv.find('input').val('');
$clonedDiv.find('input:checkbox').removeAttr('checked');
// Insert the cloned object
$clonedDiv.insertAfter("#dependant-" + oldId);
relation_input_groups.push(relation_newDiv);
}
//Cloning Function
//Validation
//submit function
var $unique = $('input[type="checkbox"]');
$unique.click(function()
{
$unique.removeAttr('checked');
$(this).attr('checked', true);
});
var result = {};
var dependants;
var dep_counter = 0;
jQuery('#submit').click(function()
{
jQuery('.dependant').each(function(k, v)
{
dep_counter++
dependants = {};
result['dependant'+dep_counter] = [dependants];
dependants['relationship'] = $(v).find('.relationship:checked').val();
});
var jsonData = JSON.stringify(result);
console.log(jsonData);
});
});
and the HTML:
<div id="dependant-1" class="dependant">
<div id="label">relationship:</div> <div id="relation-group-1"></div>
</div>
<button id="clone">clone</button>
<button id="submit">submit</button>
Thanks in advance :)
See this : http://jsfiddle.net/EEd7c/1/
var $unique = $('input[type="checkbox"]');
$unique.live("click", function() {
$(this).siblings().removeAttr('checked');
$(this).attr('checked', true);
});
Yet Live is deprecated...
Or
$(document).on("click", 'input[type="checkbox"]', function() {
$(this).siblings().removeAttr('checked');
$(this).attr('checked', true);
});
The reason why it does not work is you are not attaching the click events to the new cloned elements.
$(document).on("click", 'input[type="checkbox"]', function() {
jQuery(this).siblings(":checked").removeAttr('checked');
});
var $unique = $('input[type="checkbox"]');
$unique.live('click',function() {
$(this).closest('div').find('input[type="checkbox"]').removeAttr('checked');
$(this).attr('checked', true);
});
Using live to register the event handler to dynamically created elements. $unique variable will contain only the initial set of checkboxes.
Related
I am stuck with a problem. I want to add call functions based on selection in radio button. But one of radio buttons doesn't work at all (not calling the function), other is not checked when clicked. Here is my code:
function clearElement(element_id){
document.getElementById(element_id).remove();
}
function createCheck(){
if (!document.getElementById('check')){
var btn = "<button onclick=\"checkData()\" id='check'>Check</button>";
document.getElementById("added").innerHTML += btn;
}
}
function addElements(){
var added0 = "<p>Choose the filling method:</p><br>";
var added1 = "<input type=\"radio\" value='Auto' id='auto' name=\"auto_manual\">I have ID</input>";
var added2 = "<input type=\"radio\" value='Manually' id='manual' name=\"auto_manual\"> Enter data manually</input><br>";
var added3 = "<p>Identification Code</p><br><input type=text id='ID'><br>";
var added4 = "<p>Enter your email address:</p><br><input type='email' id='mail' autocomplete=\"on\"></input><br>";
var added5 = "<button onclick=\"fillIn()\">Continue</button>";
document.body.innerHTML += "<div id=\"added\">" + added0 + added1 + added2 + added3 + added4 + added5 + "</div>";
var f0 = document.getElementById('auto');
var f1 = document.getElementById('manual');
f0.onclick = function() { createCheck();};
f1.onclick = function() { clearSelect('check');};
}
I want it to work the following way: if a user chooses "I have ID" option, the radio button is checked and the button "Check" will be created. If "Enter data manually", the button "Check" will disappear if exists.
Could you, please, help me with it?
Update (HTML):
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<title>Demo Web App</title>
</head>
<body>
<h1>Template Creator Bot</h1> <br> <br>
<script>
...
</script>
<div id='change'>
<select name="docs" id="selectedTemplate">
<option value="Order">Order</option>
<option value="Complaint">Complaint</option>
<option value="Other">Other</option>
</select>
<button onclick="addElements()">Next</button>
</div>
</body>
</html>
It would be better if you made the button element once and just toggled its visibility on demand.
There are also better strategies to compose dynamic html on your DOM instead of using innerHTML like using <template> or creating elements with document.createElement().
By the way, addressing specifically your issue here, I made a demo that adds the button in the main addElements() routine, and two functions: showButton() and hideButton() that will be called by the click event handlers added to the two radio options.
addElements();
function showButton(){
const target = document.getElementById('check');
if (target.classList.contains('hide'))
target.classList.remove('hide');
}
function hideButton(){
const target = document.getElementById('check');
if (!target.classList.contains('hide'))
document.getElementById('check').classList.add('hide');
}
function addElements(){
var added0 = "<p>Choose the filling method:</p><br>";
var added1 = "<input type='radio' value='Auto' id='auto' name='auto_manual'>I have ID</input>";
var added2 = "<input type='radio' value='Manually' id='manual' name='auto_manual'>Enter data manually</input><br>";
var added3 = "<p>Identification Code</p><br><input type=text id='ID'><br>";
var added4 = "<p>Enter your email address:</p><br><input type='email' id='mail' autocomplete='on'></input><br>";
var added5 = "<button onclick='fillIn()'>Continue</button>";
var added6 = "<button class='hide' onclick='checkData()' id='check'>Check</button>";
document.body.innerHTML +=
"<div id='added'>" + added0 + added1 + added2 + added3 + added4 + added5 + added6 + "</div>";
/*
Here adding the click event listener for the two radio options..
in the rest of your generated html you used the approach of defining handlers on html
so it's not clear why here you opted to do it programmatically for the radio options..
Anyway I only slightly changed the approach using addEventListener instead.
*/
var f0 = document.getElementById('auto');
var f1 = document.getElementById('manual');
f0.addEventListener('click', function() { showButton();});
f1.addEventListener('click', function() { hideButton();});
}
.hide{
display: none;
}
input[type=radio]{
cursor: pointer;
}
I'm trying to do a form field validation. I got the text fields validation working from here, but not for the radio buttons as I am unsure of where I did wrong.
HTML:
<div>
<label>Gender:</label>
<input type="radio" name="gender" class="gender" value="Female" >Female</input>
<input type="radio" name="gender" class="gender" value="Male" >Male</input> <br/>
<span class="error">This field is required</span>
</div>
jQuery:
$('.gender').on('input', function() {
var input = $( this );
var is_checked = $("input[name=gender]:checked").length != 0;;
if (is_checked) {$('.gender').removeClass("invalid").addClass("valid");}
else {$('.gender').removeClass("valid").addClass("invalid");}
});
This is the real-time validation code which I played around on. It does not work however. When submitting the form, my error message still shows up regardless of which radio button I choose.
$("#studentsform").submit(function(event) {
var form_data = $("#studentsform").serializeArray();
var error_free = true;
for (var input in form_data){
var element = $("#"+form_data[input]['name']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid) {error_element.removeClass("error").addClass("error_show"); error_free = false;}
else {error_element.removeClass("error_show").addClass("error");}
}
if (!error_free) {
event.preventDefault();
}
else {
idcount++
var Surname = $('#surname').val();
var Name = $('#name').val();
var Gender = $('.gender:checked').val();
var Addr = $('#address').val();
var Email = $('#email').val();
var Phone = $('#phone').val();
$("#tblData tbody").append( "<tr>"+ "<td>" + idcount + "</td>"+ "<td>" + Surname + "</td>"+
"<td>" + Name + "</td>"+
"<td>" + Gender + "</td>"+
"<td>" + Addr + "</td>"+
"<td>" + Email + "</td>"+
"<td>" + Phone + "</td>"+
"<td><button class='btnEdit'>Edit</button><button class='btnDelete'>Delete</button></td>"+ "</tr>");
$(".btnEdit").bind("click", Edit);
$(".btnDelete").bind("click", Delete);
}
});
After checking all real-time validation, on the submit button I do the code above, which is to double check for validations and if it is error free, i append all the inputs into a row.
Preview:
As you can see from the picture above, even after clicking on Insert, my error message still shows up.
The author's code are very structured, but if anyone has a better and simpler way, could you please provide me a sample solution?
Much thanks!
Looks like you need
$("input[name=gender]").prop("checked");
which will return a boolean matching the checked value
Edit:
If you want to keep your code the same, you need to add the .valid class to all the gender-classed inputs. This way, when you check one radio, it will make both valid, and you shouldn't get an error.
$('.gender').on('input', function() {
var input = $( this );
var is_checked = $("input[name=gender]:checked").length != 0;
if (is_checked){
$('.gender').removeClass("invalid").addClass("valid");
} else {
$('.gender').removeClass("valid").addClass("invalid");
}
});
I have an issue here because when I'm saving my data I can get the value of the option box but upon clicking the edit button its the same.. I want to do is it will become the option box with the value showing first
Heres my fiddle: http://jsfiddle.net/te2wF/32/
Heres my code:
function Edit(){
var par = $(this).parent().parent(); //tr
var tdName = par.children("td:nth-child(1)");
var tdAge = par.children("td:nth-child(2)");
var tdGender = par.children("td:nth-child(3)");
var tdButtons = par.children("td:nth-child(4)");
tdName.html("<input type='text' id='txtName' value='"+tdName.html()+"'/>");
tdAge.html("<input type='text' id='txtage' value='"+tdAge.html()+"'/>");
tdGender.html(tdGender.html());
tdButtons.html("<input type='button' value = 'Save' class='btnSave'/><input type='button' value='Delete' class='btnDelete'/>");
$(".btnSave").bind("click", Save);
$(".btnEdit").bind("click", Edit);
$(".btnDelete").bind("click", Delete);
};
Working Demo
Few issues resolved:
1. Updated Edit function to provide a select option to edit the selection with last selection selected.
function Edit() {
var par = $(this).parent().parent(); //tr
var tdName = par.children("td:nth-child(1)");
var tdAge = par.children("td:nth-child(2)");
var tdGender = par.children("td:nth-child(3)");
var tdButtons = par.children("td:nth-child(4)");
tdName.html("<input type='text' id='txtName' value='" + tdName.html() + "'/>");
tdAge.html("<input type='text' id='txtage' value='" + tdAge.html() + "'/>");
if(tdGender.html().toLowerCase() == "female") {
tdGender.html("<select class='gender'><option></option><option>Male</option><option selected>Female</option></select>");
} else {
tdGender.html("<select class='gender'><option></option><option selected >Male</option><option >Female</option></select>");
}
tdButtons.html("<input type='button' value = 'Save' class='btnSave'/><input type='button' value='Delete' class='btnDelete'/>");
$(".btnSave").bind("click", Save);
$(".btnEdit").bind("click", Edit);
$(".btnDelete").bind("click", Delete);
};
2. Your code was not able to find isNumberKey function. So, I moved it outside the scope so that its accessible from everywhere.
3. In your Add function, the select markup contained an additionally >. Removed it in my code.
Here you have: http://jsfiddle.net/edgarinvillegas/te2wF/33/
Main 2 changes are that we're storing the select html in a var:
var genderSelectHtml = "<select class='gender'><option></option><option value='Male'>Male</option><option value='Female'>Female</option></select>";
And then when editing, this recreates the select:
$(genderSelectHtml).val(tdGender.html()).appendTo(tdGender.empty());
Cheers, from La Paz, Bolivia
I want to add some html data to the end of a div container.
Currently, I do it with using innerHtml:
<script language="javascript">
var addid = 0;
function addInput(id){
var docstyle = document.getElementById('addlist').style.display;
if(docstyle == 'none')
document.getElementById('addlist').style.display = '';
addid++;
var text = "<div id='additem_"+addid+"'><input type='text' size='100' value='' class='buckinput' name='items[]' style='padding:5px;' /> <a href='javascript:void(0);' onclick='addInput("+addid+")' id='addlink_"+addid+"'>add more</a></div>";
document.getElementById('addlist').innerHTML += text;
}
</script>
<div id="addlist" class="alt1" style="padding:10px;">
New list items are added to the bottom of the list.
<br /><br />
</div>
The problem is that the value that was entered in the input fields is removed once another input field is added.
How can I add content without and keep the entered data?
PS: I do not use jquery.
innerHTML changes reset form elements. Instead use appendChild. See this demo http://jsfiddle.net/5sWA2/
function addInput(id) {
var addList = document.getElementById('addlist');
var docstyle = addList.style.display;
if (docstyle == 'none') addList.style.display = '';
addid++;
var text = document.createElement('div');
text.id = 'additem_' + addid;
text.innerHTML = "<input type='text' value='' class='buckinput' name='items[]' style='padding:5px;' /> <a href='javascript:void(0);' onclick='addInput(" + addid + ")' id='addlink_" + addid + "'>add more</a>";
addList.appendChild(text);
}
Take a look at this http://reference.sitepoint.com/javascript/Node/appendChild
So something like
document.getElementById('addlist').appendChild(text);
i am using this code to access all the hidden elements from a form:
function get_hidden_val(ids,form_id)
{
var get_check_val = document.getElementById(ids);
if(get_check_val.checked){
var div = $('<div></div>')
.appendTo('form#bulk_add_cart')
.attr('id',"bulk_"+form_id)
$("form#" +form_id).find('input[type="hidden"]').each(function(){
var value =$(this).val();
var name = $(this).attr("name");
var tags = "<input type='hidden' value='" + value + "' name='"+name+"'>";
$('div#' +form_id).append(tags);
});
}
else
{
$("form#bulk_add_cart").find('div#' +form_id).remove();
}
}
My problem is when I click the first checkbox it give me the result but when i click the second checkbox it doesn't and also the another problem is when i click first checkbox it shows total hidden elements but when i second time checked it, it show 4 less ?
Please suggest a solution.
Thanks
#user704302: Missing >, update var tags to --
var tags = "<input type='hidden' value='" + value + "' id='"+id+"'>";