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
Related
I have a dynamic input field that gets appended after a plus button.
The corresponding id of these fields are answer0, answer1, answer2 and so on. That means after button click the id will be dynamically appended to the text field.
Now I want to validate these fields. My validation code is as follows
function showValidation(response) {
var respArray = JSON.parse(response.responseText).errors;
for(var i=0;i<=(Object.keys(respArray).length);i++){
var optionss= 'Enter Answers.';
if($("#answer"+i).val()==''){
$('#answer'+i+' + span').html('');
$('#answer'+i).after('<span class="' + errTextboxClass + '" style="color:#e03b3b">' + optionss+ '</span>');
$('#answer'+i).focus();
}
}
}
I am checking till response error length. But before giving values in these fields, validation works properly(fig 1). But if I enter values for first 2 fields as in the image above, the validation message does not shows for the third field (fig 2). Because at this stage the id is answer2 and the loop 'i' value checks 0 first and next checks 1. So inside loop answer0 and answer1 are having values so the validation stops there. I need to get validation for the next fields too. Thanks in advance.
My HTML and corresponding append function
<input class="form-control" name="answer0[]" id="answer0" placeholder="OPTION 1">
<a class="add-option" onclick="AppendOption()"><img src="{{asset('admin/images/icn-add-option.png')}}" alt=""></a>
function AppendOption(){
var k=1;
$('#appendOption').append('<div class="form-group row"><div class="col-md-4"><input class="form-control" name="answer0[]" id="answer'+k+'" placeholder="OPTION" ></div></div>');
k++;
}
In your AppendOption function, you set k=1 This is an invalid option once you reach the third entry (option 2). You should instead detect that, better yet still make it context sensitive when it executes. I did this by adding a answer-item class and detecting how many we have and using that number instead.
I wrapped all this in a <div id="options-container"> so I would have a place to hook the event handler (delegateTarget) https://api.jquery.com/event.delegateTarget/
I would not have used an ID here and instead used classes, but that is not part of the question but more rather the cause of it.
$('.options-container').on('click','.add-option',function(event){
let k= $(event.delegateTarget).find('.answer-item').length;
$(event.delegateTarget).append('<div class="form-group row"><div class="col-md-4"><input class="form-control answer-item" name="answer0[]" id="answer' + k + '" placeholder="OPTION" ></div></div>');
});
function showValidation(response) {
var respArray = JSON.parse(response.responseText).errors;
for (var i = 0; i <= (Object.keys(respArray).length); i++) {
var optionss = 'Enter Answers.';
if ($("#answer" + i).val() == '') {
$('#answer' + i + ' + span').html('');
$('#answer' + i).after('<span class="' + errTextboxClass + '" style="color:#e03b3b">' + optionss + '</span>');
$('#answer' + i).focus();
}
}
}
<div id="options-container">
<input class="form-control answer-item" name="answer0[]" id="answer0" placeholder="OPTION 1">
<a class="add-option"><img src="{{asset('admin/images/icn-add-option.png')}}" alt=""></a>
</div>
If the fields are required you should mark them as required otherwise you validate every field. In your case another way for validating could look like this
function showValidation(response) {
var respArray = JSON.parse(response.responseText).errors;
$('.form-group input.form-control').each(function(){
if ($(this).val() == '') {
$(this).next('span').html('');
$(this).after('<span class="' + errTextboxClass + '" style="color:#e03b3b">' + optionss+ '</span>');
$(this).focus();
}
});
}
Since I don't know how and where the showValidation() is called I can't improve it further.
I tried to display the error messages inside an input array loop and I got the answer.
var result = document.getElementsByTagName("input");
var optionss= 'Enter Answers.';
for (var j = 0; j < result.length; j++) {
if($("#answer"+j).val()==''){
$('#answer'+j+' + span').html('');
$('#answer'+j).after('<span class="' + errTextboxClass + '" style="color:#e03b3b">' + optionss+ '</span>');
$('#answer'+j).focus();
}
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'm trying to populate div with select option but i don't really now where to start...
i have some code to live edit the "title" of the div, but now i want to add to a specific div his option...
Here's the code that i have for now:
var rooms = $("#howmanyrooms").val();
var roomcounter = 1;
$(".design-your-system-page-playground-container").show();
for (var i = 0; i < rooms; i++) {
// $("<div class='appendeddiv'>Room-" + roomcounter++ + "</div>").appendTo(".housecontainer");
// $("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id'></div></br>").appendTo(".infoncontainer");
//
$("<div class='design-your-system-page-rooms targetDiv_" + roomcounter + "'>Room-" + roomcounter + "</div>").appendTo(".design-your-system-page-house");
$("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id' class='textInput' lang='targetText_" + roomcounter + "'> <select>Heating<option value='radiator'>Radiator</option><option value='underfloor'>Underfloor</option><option value='electric'>Electric</option></select> <select class='design-your-system-number-of-radiator-select'><option value='0'>0</option><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option><option value='9'>9</option></select> <span>Do you want the room to be smart (footprint) ?<input type='radio' name='smart-yes' value='smart-yes'>Yes</input> <input type='radio' name='smart-no' value='smart-no'>No</input></div></br>").appendTo(".design-your-system-page-edit-room-container");
roomcounter++;
};
if ($('.design-your-system-page-house').find('.design-your-system-page-rooms').length) {
$("#buttonaddrooms").hide();
}
$("input.textInput").on("keyup", function () {
var target = $(this).attr("lang").replace("Text", "Div");
$("." + target).text($(this).val());
});
as you can see, when i click the button, i'll append to the parent as many child divs as the value typed into the textbox and i also create the same number of "row" containing the name and other option (two select and a radio)
i'm already able to live edit the name of the ralative div, but now i want to add to that div also the other options
here a jsfiddle to help you understand what i have and what i want:
http://jsfiddle.net/3cyST/
if is not clear please tell me.
thanks
please check this fiddle:
i made your target variable global to be reusable, i also added a class for your first select element which is selecting
ive updated it and it now appends the value of your test onchange using:
$("select.selecting").on("change", function () {
$("." + target).append($(this).val());
});
you can work for the rest now.
EDIT(for the question of OP on the comment) :
to get value of radio button i'll give you 2 ways :
in Javascript :
if (document.getElementById('ID_OF_RADIO').checked) {
rate_value = document.getElementById('ID_OF_RADIO').value;
}
in jQuery :
$("input[name=RADIO_NAME]:checked").val();
give the select an id, then use
$("#id").on("change",function(){
console.log(this.value);
//whatever you want to do with the value
})
...same for the radio buttons and other options...also note that the radio buttons shouldn't have different names:
<input type='radio' name='radio_{put id here}' value='yes'>Yes</input>
<input type='radio' name='radio_{put id here}' value='no'>No</input>
another thing for the readabillity of the code: try using a template....just put a <noscript> with an id in the code...use some distinctive syntax to put placeholders in it, and replace them at runtime:
HTML:
<noscript id="template">
RoomName: <input type="text" id="roomName_%ROOMID%" />
Do you want...
<input type='radio' name='radio_%ROOMID%' value='yes'>Yes</input>
<input type='radio' name='radio_%ROOMID%' value='no'>No</input>
</noscript>
JS:
for (var i = 0; i < rooms; i++) {
var tplcode = $("#template").html();
tplcode = tplcode.replaceAll("%ROOMID%",roomcounter);
$($.pareHTML(tplcode)).appendTo(".design-your-system-page-edit-room-container");
$("input[name='radio_"+roomcounter+"']").on("change",function(){
console.log("user wants:" + $("input[name='radio_"+roomcounter+"'][checked]").val())
});
roomcounter++;
}
// these functions help replacing multiple occurances
String.prototype.replaceAll = function(find,replace){
return this.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
//escapse all regEx chars, so the string may be used in a regEx
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
Fiddle: http://jsfiddle.net/3cyST/4/
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();
});
}
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+"'>";