jquery uncertain error? - javascript

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+"'>";

Related

How to put required validation in javascript innerhtml input box

function edit_row(id)
{
document.getElementById("monthly_val"+id).innerHTML="<input type='text' id='monthly_text"+id+"' value='"+monthly+"' onkeyup='this.value=Comma(this.value)' 'required'>";
}
The above code is an example of my input field and i want to put required validation so that the data will not be saved when the field is empty.
Try this...
var a = document.getElementById("monthly"+id),
b = document.createElement("INPUT");
b.setAttribute("pattern", "regexp string");
b.setAttribute("formnovalidate", " false");
b.setAttribute("type", "text");
//add other attributes
a.appendChild(b);
/*
Just replace the regexp string*/
if you have textbox id then you can easily find and then you can check input empty or not. you need use this process before saving data.
document.getElementById("monthly_val" + id).innerHTML = "<input type='text' id='monthly_text" + id + "' value='" + monthly + "' onkeyup='this.value=Comma(this.value)'>";
if ($('#monthly_text' + id + '').val() == '') { alert('wala'); }
use this. it helps you

How to validate radio button on HTML forms using jQuery?

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

how to make input fields editable?

I have this fiddle which is having user tab.In user tab ,there are three fields which accepts name,mobile and email.When a user fills all the three and hits add button then a row is inserted.Now i want to make the new added row editable.This means that I want to keep 2 bootstrap buttons edit and delete.So if delete is pressed then the entire row will be deleted and if edit is pressed then the entire will be editable where user can change the mobile number,name and email.Can any body please tell me how to do.
This js code adds new rows
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" unchecked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
val++;
} else {
alert("please fill the form completely");
}
This question is so specific to the OP scenario, so i will try to make the answer a bit more general.
I'm no expert here, but it seems you already capture the user's input and cloned it when they click Add to a new td. Therefore from what I understood is that you need to edit/delete the data from the new created td.
We have a table that contains several fields. We want to apply the following action on them
1- Add
2- Edit
3- Delete
Maybe this isn't the best practice, in short, my approach for this was to insert two spans for each data value:
One hidden that contains an input text field (inputSpan).
Another just contains plain text value (dataSpan).
Whenever you want to edit, dataSpan (just a data container) will disappear and inputSpan (text input field) appears instead enabling you to edit the text field. Once you edit and click Save the data in the text field will be cloned to replace the data in dataSpan. So basically dataSpan is just a reflection to inputSpan text field.
Here is an updated demo:
JSFiddle >> FullView Fiddle
I suggest for readability purposes, you break your code down into small function, it will make life easier, just sayin. So here general logic for your idea:
deleteRow = function (trID) {
// delete code goes here, remove the row
$(trID).remove();
}
manageEdit = function (tdNo) {
if ($("#edit-btn" + tdNo).html() === "Edit") {
$("#save-btn" + tdNo).show();//show save button
$("#edit-btn" + tdNo).html("Cancel");//change edit to cancle
editRow(tdNo);//call edit function
} else if ($("#edit-btn" + tdNo).html() === "Cancel") {
$("#save-btn" + tdNo).hide();//hide save button
$("#edit-btn" + tdNo).html("Edit");//change back edit button to edit
cancelEditRow(tdNo);
}
}
editRow = function (tdNo) {
$(".inputSpan" + tdNo).show();//show text input fields
$(".dataSpan" + tdNo).hide();//hide data display
}
cancelEditRow = function (tdNo) {
//looop thru 3 input fields by id last digit
for (var i = 0; i < 3; i++) {
//get input span that contain the text field
var inputSpan = $("#inputSpan" + tdNo + "-" + i);
//get the data span that contain the display data
var dataSpan = $("#dataSpan" + tdNo + "-" + i);
//text field inside inputSpan
var textField = inputSpan.find('input:text');
inputSpan.hide();//hide input span
textField.val(dataSpan.html());//take original data from display span and put it inside text field to cncle changes.
dataSpan.show();//show data span instead of edit field
}
}
saveRow = function (tdNo) {
//same as edit, but we reverse the data selection.
for (var i = 0; i < 3; i++) {
var inputSpan = $("#inputSpan" + tdNo + "-" + i);
var dataSpan = $("#dataSpan" + tdNo + "-" + i);
var textField = inputSpan.find('input:text');
inputSpan.hide();
dataSpan.html(textField.val());//take data from text field and put into dataSpan
dataSpan.show();
}
$("#edit-btn" + tdNo).html("Edit");//change text to edit
$("#save-btn" + tdNo).hide();//hide same button.
}
Here where I add the spans:
var tdCounter = 0;
$(".span4").each(function () {
var tid = val+"-"+tdCounter;
$tr.append("<td id='#mytd"+tid+"'>
<span id='inputSpan"+tid+"' class='inputSpan"+val+"' style='display:none'>
<input type='text' id='#input"+tid+"' value='"+ $(this).val() + "' /></span>
<span id='dataSpan"+tid+"' class='dataSpan"+val+"'>"+$(this).val()+"</td>");
tdCounter++;
});
Here I just append the buttons to call the functions, each button works for it's own row:
$tr.append("<td><botton id='edit-btn" + val + "' class='btn' onclick=manageEdit('" + val + "');>Edit</botton></td>");
$tr.append("<td><botton style='display:none' id='save-btn" + val + "' class='btn' onclick=saveRow('" + val + "');>Save</botton></td>");
$tr.append("<td><botton id='delete-btn" + val + "' class='btn' onclick=deleteRow('" + trID + "');>Delete</botton></td>");
Below is a sample function, it wont do everyhing you need, but it shows the jquery functions and one possibility how to do it. I only enabled editing name field, and deleting.
You would have to add other fields, + copy id data for the input.
js Fiddle
window.deleteRow = function (tar) {
$(tar).parent().remove();
}
window.editRow = function (tar) {
var row = $(tar).parent(),
cells, name;
cells = row.find("td");
name = $(cells.get(1)).text();
$(cells.get(1)).text('');
$(cells.get(1)).append('<input type="text" value="' + name + '">');
}
window.saveData = function() {
var data = {};
data.name = "some name";//get this from your input
data.email= "some email";//get this from your input
data.phone= "some phone";//get this from your input
$.get("http://yourphpsite.com", data, function(data, status) {
//data contains your server response
if (data.somepositiveservermessage) {
$("#user_notification_field").text("data saved");
$("#user_notification_field").show();
});
}

jQuery input forms issue

I'm currently working on some input forms in JavaScript, and I've edited by script so that once the user enters the number of forces for a problem, new input text fields show up per number, also there is a button which is added at the end of that. The issue is when I try and click this button, I try and use the .map function to start all text field values into it and nothing is happening.
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
prompt("forces");
});
As you can see my forceRecording function is working and creates a new row with new text input fields per the numofforces but once I try clicking the forceButton to enter the values into my forces array nothing happens. Any idea what could be causing this?
You are missing the closing paranthesis around your code here
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){return $(this).val()
});
It should be like this
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val();
});
});
And don't use the id instead use a class name
$('#forceButton').click(function(){
forces=$(".newR").map(function(){
return $(this).val();
});
});
Apply the class to input field like this
<input type="text" name="forceItem" class="newR"/>
I have absolutely no idea what you're trying to achieve, but maybe this will help:
function forceRecording(numofforces, $this) {
var addRows = '<tr id="newRows">';
for (var i = 1; i <= numofforces; i++)
addRows += '<td>Force ' + i + ': </td><td><input type="text" name="forceItem" /></td>';
addRows += '<td><input type="button" class="button" id="forceButton" value="Add!" /></td></tr>';
$this.closest('tr').after(addRows);
}
$('#forceButton').click(function() {
forces = $(this).parent().parent().filter('input[name="forceItem"]').map(function() { return $(this).val(); });
});

value of hidden input is always 0

I am having trouble getting the correct value in my hidden input.
Below I have a form which gets appended into a table everytime he user clicks a button:
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target_image' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"<p class='imagef1_upload_form' align='center'><br/><span class='msg'></span><label>" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"<input type='hidden' class='numimage' name='numimage' value='" + GetFormImageCount + "' /></p>" +
"<iframe class='upload_target_image' name='upload_target_image' src='#' style='width:0px;height:0px;border:0px;solid;#fff;'></iframe></form>");
$image.append($fileImage);
Now this is the problem I am recieving and it deals with the hidden input in the form:
<input type='hidden' class='numimage' name='numimage' value='" + GetFormImageCount + "' />
Lets say I append two forms into a table, one form in row 1 (value in hidden input should be 1) and one form in row 2 (value in hidden input should be 2).
The problem is that there is no value in either form. The value of both forms are still 0. What do I need to include in code below to be able to include the correct value for the correct form?
Below is the code:
...//form code from top goes here
//CODE BELOW INCREMENTS A QUESTION NUMBER AND INCREMENTS THE HIDDEN VALUE FOR EACH ROW ADDED
$('.num_questions').each( function() {
var $this = $(this);
var $questionNumber = $("<input type='hidden' class='num_questionsRow'>").attr('name',$this.attr('name')+"[]")
.attr('value',$this.val());
$qid.append($questionNumber);
});
//BELOW IS THE FUNCTION WHICH SHOULD INSERT THE VALUE FOR THE HIDDEN INPUT FOR EACH FORM
function GetFormImageCount(){
var frm = $('.imageuploadform');
if(frm[0] != undefined)
{
if(length in frm )
{
return frm.length;
}
return 1;
}
return 0;
}
Use .val() to get the value, .attr("value") gets the default value since jQuery 1.6
You miss the parenthesesneed to call the function. Try to write
<input type='hidden' class='numimage' name='numimage' value='" + GetFormImageCount() + "' />

Categories