validate dynamically added textbox - javascript

In the below code how to validate for null values for only the dynamically added text box i.e,r_score1,r_score2.........
<script>
function validate()
{
//How to validate the r_Score.. textfields
}
$(document).ready(function() {
for(var i=0;i< sen.length;i++)
{
row += '<input type="text" name="r_score'+i+'" id="r_score'+r_count+'" size="8" />';
}
$('#details').append(row);
});
</script>
<div id="details"><input type="text" name="score' id="score" size="8" /></div>
<input type="button" value="Save" id="print" onclick="javascript:validate();" />

Give the text boxes a class name and use class selector
function validate()
{
var boxes = $("#details input:text.classname");
boxes.each(function(){
var currentVal = $(this).val();
// do your validation here
});
}

$("#details input[name^='r_score']").each(function(nr){
if($(this).val() === "") alert("Field "+(nr+1)+" is empty");
});

Use live event handler for dynamically added content.

Related

checking for an empty input [duplicate]

This question already has answers here:
How to select empty inputs (value="") using jQuery
(7 answers)
Closed 6 years ago.
I am trying to get an empty input if there is one in my div using jQuery. It is not working as it should.
There are 4 empty inputs in the div.
Here is my jquery:
var firstEmpty = $('#brochureItems').find('input:text:not(:checkbox,:button):visible:first:enabled[value= ""]').first().val();
console.log(firstEmpty);
That outputs 'undefined'.
When I remove the "[value=""]", I get '(an empty string)' outputted.
I just thought of something, I am adding those inputs in dynamically with jquery on page load. Would that have something to do with it?
If I understood you right you want to get all empty inputs inside a div. To do so, try this code:
HTML
<div>
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text" value="asdsad">
</div>
JS
var firstEmpty = $("div input[type='text']").filter(function() { return $(this).val() == ""; });
or if you want take all empty:
var emptyInputs = [];
$("div input[type='text']").each(function(){
if($(this).val() == '')
emptyInputs.push($(this))
});
Here is working Fiddle: https://jsfiddle.net/xs9jagc8/
Try this:
function findEmpty(){
var div=document.getElementById('theDivID');
for(var i=0;i<div.children.length;i++){
if(div.children[i].value==''){
return div.children[i].id;
}
}
return false;
}
function verify(){
var lol = findEmpty();
if(lol===false){
//Do whatever
alert("All filled!");
} else {
alert("The first empty input is: "+lol);
}
}
<div id='theDivID'>
<input id='blah' type='text'/>
<input id='bleh' type='text'/>
<input id='qwertyuiop' type='text'/>
<input type='text'/>
</div>
<input type='button' onclick='verify();' value='Check'/>

Insert checkboxes values(name) into input with jQuery

I'm working with Symfony and I have a lot of checkboxes with different id and value, so when I check one, i want to automatically insert its value (name) into an input and when I check other insert its value in the same input:
<input type="checkbox" name="{{ent.username}}" value="{{ent.username}}">
Thanks everyone
That does not depend on Symphony.
jQuery:
$(function() { // when page loads
$("input[type='checkbox']").on("click",function() {
if (this.checked) $("#somefield").val(this.value);
});
});
Plain JS:
window.onload=function() { // when page loads
document.querySelectorAll("input[type='checkbox']").forEach(function() {
this.onclick=function() {
if (this.checked) document.getElementById("somefield").value=this.value;
}
}
}
Steps to follow:
Add change listener on each input field of checkbox type.
Get all the selected fruit by iterating each checkbox.
Set the value of selected fruits in the field.
Running sample code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" value="Banana">Banana</input>
<input type="checkbox" value="Apple">Apple</input>
<input type="checkbox" value="Mangeo">Mango</input>
<input type="checkbox" value="Orange">Orange</input>
</div>
<div>
Selected Fruit : <input type="text" id="fruit">
</div>
<script>
var fruit = $('#fruit');
$('input[type="checkbox"]').change(function(e){
fruit.val(getSelectedFruits());
});
function getSelectedFruits(){
var fruits = "";
$('input[type="checkbox"]').each(function(i,cb){
if($(this).is(":checked")){
fruits += $(this).val() + " ";
}
});
return fruits;
}
</script>

Get input value into a <form> inline

Following my code:
<script>
function getText(text){
alert(text);
}
</script>
<form action="getText(/*here function for get text*/)">
<input type="text" class="text"/>
<input type="submit"/>
<div></div>
</form>
How to get textarea value with pure javascript in the <form> where indicated?
The action attribute contains the URL that the form will be submitted to, not JavaScript.
If you want to process the form data with JavaScript, then bind a submit event handler to it. This will be fired in the context of the form, so you can access the form element via this.
You can access the form controls through the elements collection. They will have value properties containing their values.
<form action="/some/handler" id="myForm">
<textarea name="myTextArea" class="text"></textarea>
<input type="submit">
<div></div>
</form>
<script>
function getText(text){
alert(text);
}
function formSubmitHandler(evt) {
var textarea = this.elements.myTextArea;
getText(textarea.value);
}
document.getElementById('myForm').addEventListener('submit', formSubmitHandler);
</script>
You may wish to call evt.preventDefault() if you are going to handle the form processing entirely with JS (when JS is available).
If you want value from input without using selector, then you can use some thing like this,
but remember, the value your are getting from input tag should be used as a first child of form element.
<form action="">
<input type="text" class="text"/>
<input type="button" onclick="getText()" value="get value">
<div></div>
</form>
<script>
function getText(text){
var textValue = document.getElementsByTagName('input')[0].value;
alert(textValue);
}
</script>
EDIT
If you want the text from input value after pressed the enter key then you could do like this.
<form action="">
<input type="text" class="text" onkeydown="getText(event)"/>
<div></div>
</form>
<script>
function getText(event){
var textValue = document.getElementsByTagName('input')[0].value;
if(event.which == 13){
alert(textValue);
}
}
</script>
Here a little function for you
function getTextAreaByClass(lookFor) {
var i; /* I always define at the top so jslint doesn't carp */
var elems = document.getElementsByTagName("textarea");
for (i in elems) {
if((' '+elems[i].className+' ').indexOf(' '+lookFor+' ') > -1) {
return elems[i].innerHTML;
}
}
return ""; /* or return false or whatever else you want to denote not found */
}
The above will search through all the textarea tags, look for a class that matches and will return the content within the textarea.

Form login button enabled after password field has focus

hello guys I have a login page with two inputs username and password and one button. I want to put a class on that button after password field has first character filled in. How can I do that , Thank's. If is possible to do that only with css will be awesome, or a small script to add a class on that button.
<form>
Username <input type="text" name="first" id="first" /><br/><br/>
Password <input type="text" name="last" id="last" />
<br/>
</form>
<input class="crbl" type="submit" name="last" id="last" value="login button" />
css
/*Normal State*/
.crbl{
margin-top:10px;
border:1px solid #555555;
border-radius:5px;
}
/*after password field has one character filled in state*/
.class{
???
}
fiddle:
http://jsfiddle.net/uGudk/16/
You can use toggleClass and keyup methods.
// caching the object for avoiding unnecessary DOM traversing.
var $login = $('.crbl');
$('#last').keyup(function(){
$login.toggleClass('className', this.value.length > 0);
});
http://jsfiddle.net/5eYN5/
Note that IDs must be unique.
You can do that using javascript. FIrst thing you need to put on password input the following event
Password <input type="text" name="last" id="last" onkeyup="myFunction(this);"/>
Then you define the javascript function:
function myFunction(element) {
if (element.value != '') {
document.getElementById('last').attr('class','password-1');
} else {
document.getElementById('last').attr('class','password-0');
}
}
You may try like this demo
jQuery(document).ready(function(){
jQuery('#last').keyup(function(event){
var password_length =jQuery("#last").val().length;
if(password_length >= 1){
jQuery("#last_button").addClass('someclass');
}
else
{
jQuery("#last_button").removeClass('someclass');
}
});
});
This is the best way to handle the entire input, with the "on()" Jquery method.
Use the very first parent
<form id="former">
Username <input type="text" name="first" id="first" /><br/><br/>
Password <input type="text" name="last" id="last" />
<br/>
</form>
<input class="crbl" type="submit" name="last" id="last_btn" value="login button" />
Then in Jquery
$("#former").on('keydown, keyup, keypress','#last',function(e){
var value = $(this).val();
if ( value.length > 0 ) {
$("#last_btn").addClass('class'):
}else{
$("#last_btn").removeClass('class');
}
});
With "on" method you can handle many event of the input as you can see...
make sure your ID is unique.. since you have two IDs with the same name in fiddle.. i changed the password id to 'password'...
use keyup() to check the key pressed.. and addClass() to add the class..
try this
$('#password').keyup(function(){
if($(this).val()==''){
$('#last').removeClass('newclassname'); //if empty remove the class
}else{
$('#last').addClass('newclassname'); // not not empty add
}
});
fiddle here
<script type="text/javascript">
$('#YourTextBoxId').keyup(function (e) {
if ($(this).val().length == 1) {
$(this).toggleClass("YourNewClassName");
}
else if ($(this).val().length == 0) {
$(this).toggleClass("YourOldClassName");
}
})
</script>
Test this:
http://jsfiddle.net/uGudk/33/
Please consider using unique id for all form elements, and use unique input name also.
$(document).ready(function(){
$("input[name=last]").keydown(function () {
if($(this).val().length > 0){
$(this).attr("class", "class");
//or change the submit button
$("input[type=submit]").attr("class", "class");
//or if you want to enable it if originally disbaled
$("input[type=submit]").removeAttr("disabled");
}
});
});

Changing password field to text with checkbox with jQuery

How can I toggle a password field to text and password with a checkbox check uncheck?
is this what you looking for ??
<html>
<head>
<script>
function changeType()
{
document.myform.txt.type=(document.myform.option.value=(document.myform.option.value==1)?'-1':'1')=='1'?'text':'password';
}
</script>
</head>
<body>
<form name="myform">
<input type="text" name="txt" />
<input type="checkbox" name="option" value='1' onchange="changeType()" />
</form>
</body>
</html>
Use the onChange event when ticking the checkbox and then toggle the input's type to text/password.
Example:
<input type="checkbox" onchange="tick(this)" />
<input type="input" type="text" id="input" />
<script>
function tick(el) {
$('#input').attr('type',el.checked ? 'text' : 'password');
}
</script>
updated: live example here
changing type with $('#blahinput').attr('type','othertype') is not possible in IE, considering IE's only-set-it-once rule for the type attribute of input elements.
you need to remove text input and add password input, vice versa.
$(function(){
$("#show").click(function(){
if( $("#show:checked").length > 0 ){
var pswd = $("#txtpassword").val();
$("#txtpassword").attr("id","txtpassword2");
$("#txtpassword2").after( $("<input id='txtpassword' type='text'>") );
$("#txtpassword2").remove();
$("#txtpassword").val( pswd );
}
else{ // vice versa
var pswd = $("#txtpassword").val();
$("#txtpassword").attr("id","txtpassword2");
$("#txtpassword2").after( $("<input id='txtpassword' type='password'>") );
$("#txtpassword2").remove();
$("#txtpassword").val( pswd );
}
});
})
live example here
You can use some thing like this
$("#showHide").click(function () {
if ($(".password").attr("type")=="password") {
$(".password").attr("type", "text");
}
else{
$(".password").attr("type", "password");
}
});
visit here for more http://voidtricks.com/password-show-hide-checkbox-click/
I believe you can call
$('#inputField').attr('type','text');
and
$('#inputField').attr('type','password');
depending on the checkbox state.
Toggle the checkbox's focus event and determain the checkbox's status and update the field as nesscarry
$box = $('input[name=checkboxName]');
$box.focus(function(){
if ($(this).is(':checked')) {
$('input[name=PasswordInput]').attr('type', 'password');
} else {
$('input[name=PasswordInput]').attr('type', 'text');
}
})
I have the following in production. It clones a new field having the toggled type.
toggle_clear_password = function( fields ) {
// handles a list of fields, or just one of course
fields.each(function(){
var orig_field = $(this);
var new_field = $(document.createElement('input')).attr({
name: orig_field.attr('name'),
id: orig_field.attr('id'),
value: orig_field.val(),
type: (orig_field.attr('type') == 'text'? 'password' : 'text')
})
new_field.copyEvents(orig_field); // jquery 'copyEvents' plugin
orig_field.removeAttr('name'); // name clashes on a form cause funky submit-behaviour
orig_field.before(new_field);
orig_field.remove();
});
}
JQuery doesn't just let you take the type attribute and change it, at least not the last time I tried.
<html>
<head>
<script>
$(function(){
$("#changePass").click(function(){
if ($("#txttext").hasClass("hide")){
$("#txttext").val( $("#txtpass").val() ).removeClass("hide");
$("#txtpass").addClass("hide");
} else if ($("#txtpass").hasClass("hide")){
$("#txtpass").val( $("#txttext").val() ).removeClass("hide");
$("#txttext").addClass("hide");
}
});
});
</script>
<style>
.hide{display:none;}
</style>
</head>
<body>
<form id="myform">
<input type="text" id="txtpass" type='password'/>
<input class="hide" type="text" id="txttext" type='text'/>
<button id="changePass">change</button>
</form>
</body>
</html>
.attr('type') was blocked by jQuery team because it won't work with some versions of IE.
Consider using this code :
$('#inputField').prop('type','text');
$('#inputField').prop('type','password');
oncheck
$('#password').get(0).type = 'text';
onuncheck
$('#password').get(0).type = 'password';
This can be implemented much simpler:
<form name="myform">
<input type="password" name="password" />
<input type="checkbox" name="showPassword" onchange="togglePasswordVisibility()" />
</form>
<script>
function togglePasswordVisibility() {
$('#password').attr('type', $('#showPassword').prop('checked') ? 'text' : 'password');
}
</script>
Works for jQuery 1.6+

Categories