Changing form input to read only when elements reproduced - javascript

So I am pretty clueless when it comes to jQuery and just inherited someone else's code. Any help is greatly appreciated.
I have a form that is populated from a query as they add students to the form. They can have any number of students added to the form. Below is the html:
<table style="width:100%">
<tr>
<td colspan="2">
<label class="control-label" >Name</label>
<input type="text" name="name[]" value="" class="required" style="width: 290px">
</td>
<td colspan="2">
<label class="control-label" >Email</label>
<input type="text" name="email[]" value="" class="required">
</td>
</tr>
<tr>
<td colspan="2">
<label class="control-label" >Address</label>
<input type="text" name="address1[]" value="" class="required" style="width: 290px">
</td>
<td colspan="2">
<label class="control-label" >Address 2 <small>(optional)</small></label>
<input type="text" name="address2[]" value="">
</td>
</tr>
<tr>
<td colspan="1">
<label class="control-label" >City</label>
<input type="text" name="city[]" value="" style="width:120px;" class="required">
</td>
<td>
<label class="control-label" >State/Providence</label>
<input type="text" name="st_prov[]" value="" style="width:120px;" class="required">
</td>
<td>
<label class="control-label" >Postal Code</label>
<input type="text" name="zip_pc[]" value="" style="width:60px;" class="required">
</td>
<td>
<label class="control-label" >Country</label>
<input type="text" name="country[]" value="" class="required">
</td>
</tr>
<tr><td colspan="4"> </td></tr>
</table>
Here is the jQuery function that I've been trying to modify:
jQuery(function($){
var addStudent = function(data){
var studentEl = $($('.student').get(0)).clone()
studentEl.find('input').each(function(){
var field = $(this).attr('name').replace('[]','')
if ($(this).attr("name").val == 'name'){
$(this).prop("readonly", true);
}
$(this).val(data[field] || '')
})
if(data.client_no!=''){
studentEl.find('.will_update').text("Will update student information for "+data.name+'')
}
$($('.student').last()).after(studentEl)
}
})
The function creates an additional set of fields for each student populated by the database for the form to process.
I'm looking to modify the specific field for "name" to be readonly (can view but not modify but yet still submit). I've tried many other iterations but cannot get the field name in the if clause to make only that field read only.
Any help provided would be great.

The proper way of getting an attribute via jQuery is just : $(this).attr("name")
Also instead of using:
var field = $(this).attr('name').replace('[]','')
if ($(this).attr("name").val == 'name'){
$(this).prop("readonly", true);
}
Use the variable field that you already created:
var field = $(this).attr('name').replace('[]','')
if (field == 'name'){
$(this).prop("readonly", true);
}
See snippet below :
jQuery(function($) {
var addStudent = function(data) {
var studentEl = $($('.student').get(0)).clone()
studentEl.find('input').each(function() {
var field = $(this).attr('name').replace('[]', '')
if (field == 'name') {
$(this).prop("readonly", true);
}
$(this).val(data[field] || '')
})
if (data.client_no != '') {
studentEl.find('.will_update').text("Will update student information for " + data.name + '')
}
$($('.student').last()).after(studentEl)
}
$('button').click(function() {
addStudent({
client_no: 1,
name: "Ralph John "
})
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%" class="student">
<tr>
<td colspan="2">
<label class="control-label">Name</label>
<input type="text" name="name[]" value="" class="required" style="width: 290px">
</td>
<td colspan="2">
<label class="control-label">Email</label>
<input type="text" name="email[]" value="" class="required">
</td>
</tr>
<tr>
<td colspan="2">
<label class="control-label">Address</label>
<input type="text" name="address1[]" value="" class="required" style="width: 290px">
</td>
<td colspan="2">
<label class="control-label">Address 2 <small>(optional)</small>
</label>
<input type="text" name="address2[]" value="">
</td>
</tr>
<tr>
<td colspan="1">
<label class="control-label">City</label>
<input type="text" name="city[]" value="" style="width:120px;" class="required">
</td>
<td>
<label class="control-label">State/Providence</label>
<input type="text" name="st_prov[]" value="" style="width:120px;" class="required">
</td>
<td>
<label class="control-label">Postal Code</label>
<input type="text" name="zip_pc[]" value="" style="width:60px;" class="required">
</td>
<td>
<label class="control-label">Country</label>
<input type="text" name="country[]" value="" class="required">
</td>
</tr>
<tr>
<td colspan="4"> </td>
</tr>
</table>
<button>Add Student</button>

Couple problems in your code.
Use $('student').eq(0) instead of $($('.student').get(0))
You're getting the dom element from a jquery object and rewrapping it into a jquery object. The eq(index) function returns a jquery wrapped element.
You're trying to get a val property from attr("name"), which returns a string. You'll get undefined.
if ($(this).attr("name").val == 'name'){
$(this).prop("readonly", true);
}
If you're trying to find the existence of the name attribute, just do
if ($(this).attr("name")){
$(this).prop("readonly", true);
}
Lastly, you don't need to rewrap a jquery object with a jquery object.
$($('.student').last())
Jquery functions return the jquery object, meaning you can chain calls, and you don't need to rewrap it.
$('.student').last()

You can modify your code as below. Assuming your table has class student here is a working demo - Fiddle.
$(function(){
var addStudent = function(data){
var studentEl = $('.student tr:first').clone();
studentEl.find('input').each(function(){
var field = $(this).attr('name').replace('[]','');
if (field === 'name'){
$(this).prop("readonly", true);
}
$(this).val(data[field] || '')
})
if(data.client_no !== ''){
studentEl.find('.will_update').text("Will update student information for "+data.name+'')
}
$('.student').last().after(studentEl)
}
});

Related

Validate each input field Bootstrap form using javascript without hitting the submit button

I m new to JS, I have the below form I need javascript code to validate each field without clicking on submit button. Thanks in Advance
I m new to JS, I have the below form I need javascript code to validate each field without clicking on submit button. Thanks in Advance
<form action="" id = "form1"class = "form-group row">
<table class = "form-table">
<tr>
<td class = "col-sm-2 col-form-label">Name:</td>
<td><input type="text" class="form-control" id="name" placeholder="Name" value="" required="required" data-error="Please enter your full name.">
<div class="help-block with-errors"></div></td>
</tr>
<tr>
<td label for="email" class="col-sm-2 col-form-label" >Email:</td>
<td><input type="email" class="form-control" id="inputEmail3" placeholder="name#example.com" required="required">
</tr>
<tr>
<td label for="inputPhone3" class="col-sm-2 col-form-label">Phone:</td>
<td><input type="number" class="form-control" required="required" id="phone" placeholder="Phone"></td>
</tr>
<tr>
<td class = "sel1">Reason for Inquiry:</td>
<td><select class="form-control" required="required" id="sel1">
<option value="catering">Catering</option>
<option value="privateparty">Private party</option>
<option value="feedback">Feedback</option>
<option value="other">other</option>
</select>
</td>
</tr>
<tr>
<td class = "form-group">Additional Information:</td>
<td><textarea class="form-control" rows="5" id="comment"></textarea></td>
</tr>
<tr>
<td>Have you been to resturant:</td>
<td> <input type="radio" required="required" name="optradio"> Yes
<input type="radio" name="optradio"> No</td>
</tr>
<tr>
<td class = "form-check-input"> Best days to contact you:</td>
<td><input type="checkbox" required="required" name="m">M
<input class="form-check-input" type="checkbox" name="t">T
<input class="form-check-input" type="checkbox" type="checkbox" name="W">W
<input class="form-check-input" type="checkbox" type="checkbox" name="Th">Th
<input class="form-check-input" type="checkbox" type="checkbox" name="F">F</td>
</tr>
<tr>
<td></td>
<td><button class="btn btn-primary">Submit Request</button></td>
</tr>
</table>
</form>
You can use change event on your form to perform validation after any field changes with this script:
var form = document.forms.form1;
form.addEventListener('change', function() {
alert('Changed');
// Add your validation code here
});
Check the working example here
This is an example of very simple validation for name and e-mail fields, just to give you an idea how to implement it. We can add new element <div id="error-message" />, and use it to display found errors from the script:
var form = document.forms.form1;
form.addEventListener('change', function() {
document.querySelector('#error-message').innerHTML = '';
// Validate Name
const input_name = document.querySelector('#name').value;
if (input_name == "") {
document.querySelector('#error-message').innerHTML += "Name is missing<br>";
}
// Validate Email
const input_email = document.querySelector('#inputEmail3').value;
if (input_email == "") {
document.querySelector('#error-message').innerHTML += "Email is missing<br>";
}
});
Of course, you would need to implement better validation than this and decide how to display messages, but basic working example is here

Form Validation in JavaScript-html

i've built asimple webstie that contains three pages.i created a form in home page and something goes wrong with my javascript - i'm having a problem in setting a field right next to the input field with a rellevant message to the user telling him what he did wrong(prompt).
so i'm inputing below the honmePage (the form wich is in the body of the page -html) and the script its self wich includes a simple function.
My purpose is to check if user fills the field name and after that he delete it,so i want to display a red color message that tells the user that this field is requierd.
i'd be glad if someone can help me with that.
function validateName(){
var name=document.getElementById("fullName").value;
if (name.length == null)
{
nameRequiredPromt("Name Is Required",fullNamePrompt,"white");
return false;
}
}
function nameRequiredPromt(message,promtLocation,color){
document.getElementById(promtLocation).innerHTML=message;
document.getElementById(promtLocation).style.color=color;
}
<form id="form" style="color:white;">
<table>
<tr>
<td>
FullName :
</td>
<td>
<input type="text" placeholder="fullName" id="fullName"
onkeyup="validateName()" type="text"/> <label id="fullNamePrompt">aaaa
</label> <br>
</td>
</tr>
<tr>
<td>
E-mail :
</td>
<td>
<input type="email" placeholder="email" id="email"/><label
id="emailPrompt"> </label><br>
</td>
</tr>
<tr>
<td>
New Password :
</td>
<td>
<input type="password" placeholder="password" id="newPassWord"/> <label
id="PasswordPrompt"> </label><br>
</td>
</tr>
<tr>
<td>
Repeat Password :
</td>
<td>
<input type="password" placeholder="repeatedPassword"
id="repeatedPassWord"/> <label id="repeatedPassWordPrompt"> </label><br>
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" value="submit" id="submit"/> <label
id="submitPrompt"> </label><br>
</td>
</tr>
</table>
</form>
i did some checks to be sure that the script works and it did work so i think my problem is in the decleration of the lable "id".
switch
name.length == null
to
!name.length
length will be zero not null
also fullNamePrompt appears undefined
try nameRequiredPromt("Name Is Required","fullNamePrompt","white");
Fixed: name.length == null and also fullNamePrompt undefined and color: white to red
function validateName(){
var name=document.getElementById("fullName").value;
if (!name.length)
{
nameRequiredPromt("Name Is Required","fullNamePrompt","red");
return false;
}
}
function nameRequiredPromt(message,promtLocation,color){
document.getElementById(promtLocation).innerHTML=message;
document.getElementById(promtLocation).style.color=color;
}
<form id="form" style="color:white;">
<table>
<tr>
<td>
FullName :
</td>
<td>
<input type="text" placeholder="fullName" id="fullName"
onkeyup="validateName()" type="text"/> <label id="fullNamePrompt">aaaa
</label> <br>
</td>
</tr>
<tr>
<td>
E-mail :
</td>
<td>
<input type="email" placeholder="email" id="email"/><label
id="emailPrompt"> </label><br>
</td>
</tr>
<tr>
<td>
New Password :
</td>
<td>
<input type="password" placeholder="password" id="newPassWord"/> <label
id="PasswordPrompt"> </label><br>
</td>
</tr>
<tr>
<td>
Repeat Password :
</td>
<td>
<input type="password" placeholder="repeatedPassword"
id="repeatedPassWord"/> <label id="repeatedPassWordPrompt"> </label><br>
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" value="submit" id="submit" onclick="return validateName();"/> <label
id="submitPrompt"> </label><br>
</td>
</tr>
</table>
</form>
if (name && !name.length)
{
nameRequiredPromt("Name Is Required","fullNamePrompt","white");
return false;
}
first condition checks if name is null, second for checking if name.length is 0.

Disable only unwanted inputs Javascript

I have this cool piece of Javascript that disables rows and change color were input is disabled.
But I need:
If filled input #1 all other 3 inputs are disabled,
if filled input #3 all other 3 inputs are disabled,
if filled input #2 and/or #4 then inputs #1 AND #3 are disabled.
Data is coming from database.
Javascript:
$(".input").on("keypress change keyup",function(){
if($(this).val() != "")
{
$(this).parent().parent().find(".input").not($(this)).prop("disabled",true).css("background-color","#cccccc");
}
else
{ $(this).parent().parent().find(".input").prop("disabled",false).css("background-color","#ffffff");
}
});
And here is the table code:
<table>
<tr>
<td>
<input type="text" class="input" value="">
</td>
<td>
<input type="text" class="input" value="">
</td>
<td>
<input type="text" class="input" value="">
</td>
</tr>
<tr>
<td>
<input type="text" class="input" value="">
</td>
<td>
<input type="text" class="input" value="">
</td>
<td>
<input type="text" class="input" value="">
</td>
</tr>
</table>
This piece of code was made by Alexis.
Here are the codes you seek...
HTML
To avoid the issue you were having with hidden inputs etc and not knowing the nth-term of each element, use classes instead:
<table>
<tr>
<td>
<input type="hidden" class="input" value="">
</td>
<td>
<input type="text" class="input toggle all" value="">
</td>
<td>
<input type="text" class="input toggle every-other" value="">
</td>
<td>
<input type="text" class="input toggle all" value="">
</td>
<td>
<input type="text" class="input toggle every-other" value="">
</td>
</tr>
</table>
JQuery
$('body').on( 'keyup blur', '.input.toggle', function() {
var $this = $( this );
var $parent = $this.parent();
var $disable = $parent.siblings().children();
if ( $this.val() != "" )
{
if ( $this.is( '.all' ) )
{
$disable = $parent.siblings().children( '.toggle' );
}
else if ( $this.is( '.every-other' ) )
{
$disable = $parent.siblings().children( '.all' );
}
$disable.attr( 'disabled', true ).css("background-color","#ccc");
}
else
{
$disable.removeAttr('disabled').css("background-color","#fff");
}
});
And here is an example of it working.

Automatically restart a new input

I would like to think that if you do something in the first id = "benodigheden" that there is something specific then a second rule is for id = "benodigheden" I also couldn't find anything on the internet. I think you need to have java but here is my knowledge still too small for.
I hope somebody can help me.
This is my HTML:
<form action="" method="post">
<legend>Neem contact op</legend>
<table>
<tr>
<td>
<label for="Naam">Naam: </label>
</td>
<td>
<input type="text" id="Naam" name="Naam" placeholder="Naam" required="required" />
</td>
</tr>
<tr>
<td>
<label for="Email">Email :</label>
</td>
<td>
<input type="email" id="Email"name="Email" placeholder="Email" required="required" />
</td>
</tr>
<tr>
<td>
<label for="Seizoen">Seizoen: </label>
</td>
<td>
<select name="Seizoen" id="Seizoen" required>
<option value="">Kies hier je seizoen</option>
<option value="Lente">Lente</option>
<option value="Zomer">Zomer</option>
<option value="Herfst">Herfst</option>
<option value="Winter">Winter</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<hr />
</td>
</tr>
<tr>
<td>
<label for="benodigheden1">Benodigheden:</label>
</td>
<td>
<input type="text" id="benodigheden1"name="benodigheden1" placeholder="Benodigheden" required="required" />
</td>
</tr>
<tr>
<td>
<label for="ingrediënten1">Ingrediënten:</label>
</td>
<td>
<input type="text" id="ingrediënten1"name="ingrediënten1" placeholder="Ingrediënten" required="required" />
</td>
</tr>
<tr>
<td>
<label for="stappenplan">Stappenplanm:</label>
</td>
<td>
<textarea name="stappenplan" id="stappenplan" cols="40" rows="5" placeholder="Stappenplan" required="required" /></textarea>
</td>
</tr>
<tr>
<td colspan="2">
<hr />
</td>
</tr>
<tr>
<td>
<label for="Opmerking">Opmerking:</label>
</td>
<td>
<textarea name="Opmerking" id="Opmerking" cols="40" rows="5" placeholder="Opmerking" required="required" /></textarea>
</td>
</tr>
<tr>
<td>
</td>
<td>
<div class="submit"><input type="submit" value="Verzenden" name="Verzenden" /></div>
</td>
</tr>
</table>
Here is a link to JSFiddle.
If I understand correctly you want an extra line (rule?) to appear once you enter text in it, and that this should happen for those inputs that have a sequence number in their id.
For this I suggest you include jQuery and add a script that detects input changes, and adds a new input if needed, with the next available sequence number:
$(document).on('keyup change input', 'input, textarea', function() {
if (!$(this).val().replace(/\s/g, '').length) {
// no text entered, so don't add line
return;
}
var id = $(this).attr('id');
// Extract name and linenumber from id
var res = id.split(/(\d+$)/);
if (res.length < 2) {
// No line number, so don't add line
return;
}
var newId = res[0] + (parseInt(res[1]) + 1);
if ($('#' + newId).length) {
// Not the last line, so don't add line
return;
}
// Add a line, and make it non-mandatory
$(this).clone()
.attr('id', newId).removeAttr('required')
.val('')
.insertAfter(this)
.before($('<br>'));
});
Although the above can be done in pure javascript it is much more cumbersome, and harder to deal with cross-browser issues.
You can see it work in this fiddle.

Is it posible to get all the values of the text boxes with the same name?

I have a doubt in javascript. Is it posible to get the values of text boxes with the same name ?
for example
<INPUT TYPE="text" NAME="inputbox" VALUE="">
<INPUT TYPE="text" NAME="inputbox" VALUE="">
these text boxes have same name, how can i get its values by name ?
OK, lemme come to the real problem i got, hope am explaining correctly.
I have a series of text boxes which i gotta validate now. Its not a big deal to validate textboxe normally.
But this is an array of text boxes where the id of the text boxes will be available only when the fields are added dynamically by clicking on the + button. when the press button is clicked the whole set of text boxes will appear. as many times its clicked, it will get added.
So its imposible to get the values to validate with the ID, so i tried by name.
JAVASCRIPT FUNCTION
function insComep()
{
// $("#doctorPri").validationEngine("updatePromptsPosition")
// jQuery("#doctorPri").validationEngine('attach', {promptPosition : "topRight"});
rl=document.getElementById("compeTable").rows.length;
var a=document.getElementById("compeTable").insertRow(rl);
var g=a.insertCell(0);
var f=a.insertCell(1);
var m=a.insertCell(2);
var n=a.insertCell(3);
var o=a.insertCell(4);
var p=a.insertCell(5);
var q=a.insertCell(6);
var r=a.insertCell(7);
var s=a.insertCell(8);
var t=a.insertCell(9);
//var v=a.insertCel1l(11);
//var u=a.insertCell(12);
g.innerHTML='<select name="competproduct[]" style="width:86px" id="competproduct'+rl+'" class="validate[required]" ><option value="">--Select--</option><?echo $product_str;?></select>';
f.innerHTML='<input type="text" name="competcompany[]" id="competcompany'+rl+'" size="10" class="validate[required]" >';
m.innerHTML='<input type="text" name="competbrand[]" id="competbrand'+rl+'" size="10" class="validate[required]" >';
n.innerHTML='<input type="text" name="competdrug[]" id="competdrug'+rl+'" size="10" class="validate[required]" >';
o.innerHTML='<input type="text" name="competquty[]" id="competquty'+rl+'" size="2" class="validate[required,custom[integer]] text-input" >';
p.innerHTML='<input type="text" name="competprice_frm[]" id="competprice_frm'+rl+'" size="2" class="validate[required,custom[number],funcCall[getPriceFromE]] text-input" />';
q.innerHTML='<input type="text" name="competprice_to[]" id="competprice_to'+rl+'" size="2" class="validate[required,custom[number],funcCall[getPriceTo]] text-input" />';
r.innerHTML='<input type="text" name="competmrp[]" id="competmrp'+rl+'" size="2" class="validate[required,custom[number],funcCall[getMrp]] text-input"/>';
s.innerHTML='<select name="ChemistParma[]" style="width:86px" id="ChemistParma'+rl+'" style="width:86px" ><option value="">--Select--</option><?echo $chemist_str;?></select>';
t.innerHTML='<img src="media/images/details_close.png" onClick="delCompe('+rl+'); "/>';
// jQuery("#doctorPri").validationEngine('attach', {promptPosition : "topRight"});
$("#doctorPri").validationEngine('hideAll');
}
HTML
<table width="100%" id='compeTable' border='0' style='margin-left:auto;margin-right:auto;margin-top:40px;' >
<tr style="border-bottom:1px solid #999999;"><td colspan='4'>
<div style="background:;padding:3px;text-align:left; ">
<font color='black'><strong >Competitor Detail(s):</strong></font><font color="red">*</font>
</div>
</td></tr>
<tr>
<td>Product Name:<font color="red">*</font></td>
<td>Company Name:<font color="red">*</font></td>
<td>Brand Name:<font color="red">*</font></td>
<td>Drug Name:<font color="red">*</font></td>
<td> Quantity:<font color="red">*</font></td>
<td>Pricefrom Dist:<font color="red">*</font></td>
<td >Price to Dist:<font color="red">*</font></td>
<td> MRP:<font color="red">*</font></td>
<td>Chemist<font color="red">*</font><input type='button'value='+' style='width:1px' style='width:1px' onclick='frame5()'/>
</td>
<td></td>
</tr>
<tr><td> </td></tr>
<tr>
<td>
<select name='competproduct[]' id='competproduct' style="width:86px" class="validate[required]" >
<option value=''>-select Product-</option>
<? echo $product_str;?>
</select>
</td>
<td>
<input type="text" name="competcompany[]" id="competcompany" size="10" class="validate[required]" >
</td>
<td ><input type="text" name="competbrand[]" id="competbrand" size="10" class="validate[required]" >
</td>
<td><input type="text" name="competdrug[]" id="competdrug" size="10" class="validate[required]" >
</td>
<td><input type="text" name="competquty[]" id="competquty" size="2" class="validate[required,custom[integer]] text-input" >
</td>
<td>
<input type="text" name="competprice_frm[]" id="competprice_frm" size="2" class="validate[required,custom[number],funcCall[getPriceFromE]] text-input" />
</td>
<td>
<input type="text" name="competprice_to[]" id="competprice_to" size="2" class="validate[required,custom[number],funcCall[getPriceTo]] text-input" />
</td>
<td><input type="text" name="competmrp[]" id="competmrp" size="2" class="validate[required,custom[number],funcCall[getMrp]] text-input" onBlur=''/>
</td>
<td>
<select name='ChemistParma[]' id='ChemistParma' style="width:86px">
<option value=''>-select chemict-</option>
<?echo $chemist_str?>
</select></td>
<td>
<img src="media/images/details_open.png" onClick="insComep()"/>
</td>
</tr>
</table>
It's quite simple,
document.getElementsByName("inputBox");
You can use a multitude of different methods.
1) Manual traversal of childNodes etc, and checking for nodeName. This is pretty involved and requires a lot of boring code, so I won't write an example of that here.
2) document.getElementsByTagName. This can also be used on DOM nodes, so you can do something like document.getElementById("my_form").getElementsByTagName("input"), depending on how the rest of the DOM looks of course.
3) document.querySelectorAll("input"). The string argument is a full CSS selector. Some older browsers doesn't support this though.
Here is example for you with your code:
<div id="inputs">
<INPUT TYPE="text" NAME="inputbox" VALUE="asd">
<INPUT TYPE="text" NAME="inputbox" VALUE="efs">
</div>
<script>
$(document).ready(function () {
var howmany = $('#inputs').children("input").length;
alert(howmany);
for( i=0; i<= howmany-1; i++ ) {
var input = $("#inputs").children("input").eq(i).attr('VALUE');
alert(input);
}
});
</script>

Categories

Resources