How to display buttons when a text box is focused in Javascript - javascript

I have written the following code for a virtual keyboard using javascript.
Jsp page:
<form>
<label for="text">Enter Text: </label>
<input id="text" name="text" type="text" size="50" onfocus="myFunction(this)" />
<input name="" type="reset" value="Clear" />
</form>
Javascript:
function myFunction(x)
{
}
function clicked(val)
{
var txt;
txt = document.getElementById('text').value;
if(val != 'B')
{
txt = txt + '' + val;
}
else
{
txt = txt.substr(0,(txt.length)-1);
}
document.getElementById('text').value = txt;
}
$(".dialog").dialog({
autoOpen: false,
height: 200,
width: 930,
modal: false,
draggable: true,
resizable: true,
buttons : {
"ESC":function(){
var val="Esc";
clicked(val);
},
"1":function(){
var val="1";
clicked(val);
},
"Tab":function(){
var val="T";
clicked(val);
},
"Caps":function(){
var val="q";
clicked(val);
},
"Shift":function(){
var val="";
clicked(val);
},
"B":function(){
var val=" ";
clicked(val);
},
},
});
When the text box is focused display dialog like keyboard, when i click some button its entered button value in textbox except Caps,Shift,Enter and Tab.
Please provide the required code for those Caps,Shift,Enter,Tab .
I'm not sure how to maintain code in clicked(val) method .

Use jQuery:
$("#text").on("focus", function() {
$("#button1").show();
$("#button2").show();
});
I just noticed you commented on somebody else's answer saying you want to create buttons with JS dynamically.
Here's a way to do it:
HTML:
<div id="myDiv"></div>
jQuery:
var myBtn = $('<button/>', {
text: 'Awesome button',
click: function () {
alert("Hello!");
}
});
$("#myDiv").append(myBtn);
DEMO

I hope the following example would be helpful:
<script type="text/javascript">
<!--
function fClose() {
document.getElementById('divWithButtons').style.display = 'none';
}
function myFunction(x) {
document.getElementById('divWithButtons').style.display = '';
}
//-->
</script>
<div style="display:none; position:absolute; top: 100px; left: 100px; background-color: #eee;" id=divWithButtons>
<input type=button value=Really onclick=fClose() style="margin: 100px">
<input type=button value="Why not" onclick=fClose() style="margin: 100px">
</div>
<form>
<label for="text">Enter Text: </label>
<input id="text" name="text" type="text" size="50" onfocus="myFunction(this)" />
<input name="" type="reset" value="Clear" />
</form>

Wrtie the function like this:
function myFunction(x)
{
document.getElementById("btn1").style.display="block";
document.getElementById("btn2").style.display="block";
}
Also set the id of buttons as well.
<form>
<label for="text">Enter Text: </label>
<input id="text" name="text" type="text" size="50" onfocus="myFunction(this)" />
<input name="" type="reset" value="Clear" />
<button id="btn1" class="btn">Btn1</button>
<button id=btn2" class="btn">Btn2</button>
</form>
Hope this will work for you.

Try this
HTML
<form>
<label for="text">Enter Text: </label>
<input id="text" name="text" type="text" size="50" />
<input name="" type="reset" value="Clear" />
</form>
Script
$(function() {
$("#text").focusin(function() {
$('form').append('<button class="btn">Btn1</button>\
<button class="btn">Btn2</button>'); // It will add dynamically two buttons
$(".btn").show();
})
});
DEMO

try this with jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery( document ).ready(function() {
jQuery("#text").focus(function() {
jQuery('.btn').show();
});
// if you want button disappear after focus out
jQuery("#text").focusout(function() {
jQuery('.btn').hide();
});
});
</script>
...
<form>
<label for="text">Enter Text: </label>
<input id="text" name="text" type="text" size="50" />
<input name="" type="reset" value="Clear" />
<input class="btn" type="button" value="button2" name="btn2" style="display:none;"/>
<input class="btn" type="button" value="button1" name="btn1" style="display:none;"/>
</form>

Related

Why is my button color not changing on command?

I "made" this script:
<script>
export default {
name: "Form"
}
var backRGB = document.getElementById("color").value;
document.getElementById("color").onchange = function() {
backRGB = this.value;
console.log(backRGB);
document.getElementById("orgButton").color = backRGB;
}
</script>
It supposedly checks if the color picker with 'color' has changed and if it does it changes the button 'orgButon' to the color that was picked. However, it's not working. I think that even the console.log isn't working.
Here's the template:
<template>
<div>
<div class="formulario">
<h1>Criar Organização</h1>
<form>
<div><input class="long" type="text" name="orgName" id="orgName" placeholder="Nome" minlength="5" maxlength="20"></div>
<div>
<input class="short" type="text" name="orgAbb" id="orgAbb" placeholder="Abreviatura" minlength="3" maxlength="4">
<input type="color" id="color" value="#f6b73c">
</div>
<input class="button" type="button" id="orgButton" value="Criar">
</form>
</div>
</div>
</template>
The code above is all in Form.vue.
If the JS is above the HTML, it will fail because document.getElementById("color") doesn't exist yet so it can't set its onchange event handler.
The following code worked for me:
<div>
<div class="formulario">
<h1>Criar Organização</h1>
<form>
<div><input class="long" type="text" name="orgName" id="orgName" placeholder="Nome" minlength="5" maxlength="20"></div>
<div>
<input class="short" type="text" name="orgAbb" id="orgAbb" placeholder="Abreviatura" minlength="3" maxlength="4">
<input type="color" id="color" value="#f6b73c">
</div>
<input class="button" type="button" id="orgButton" value="Criar">
</form>
</div>
</div>
<script>
var backRGB = document.getElementById("color").value;
document.getElementById("color").onchange = function() {
backRGB = this.value;
console.log(backRGB);
document.getElementById("orgButton").style.backgroundColor = backRGB;
}
</script>
I see you are using vue.js in your code. This solution makes use of two-way binding with v-model
<template>
<div id="app">
<input type="color" v-model="color">
<p>{{ color }}</p>
<button :style="{color}">BUTTON</button>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
color: ""
};
},
};
</script>
Open this codepen for demonstration
EDIT: more info on reactive styles here

How do I assign value of the clicked button

I have the following on jsfiddle. What I need to accomplish is when I click on a button the respective value is inserted in the blank.
https://jsfiddle.net/aminbaig/jefee77L/
Here is the Code:
HTML:
There is <span id="title">___________</span> wrong with this world!
<p>
Choose the appropriate word
</p>
<input type="submit" id="myTextField" value="something" onclick="change()" />
<input type="submit" id="byBtn1" value="Truck" onclick="change()" />
<input type="submit" id="byBtn2" value="Trash" onclick="change()" />
Javascript:
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title');
title.innerHTML = myNewTitle;
}
You can do like this
JS
get the value of the button from the function parameter
function change(value) {
var title = document.getElementById('title');
title.innerHTML = value;
}
HTML
change button type='submit' to type='button', Also pass the value as the function parameter
<input type="button" id="myTextField" value="something" onclick="change(this.value)" />
<input type="button" id="byBtn1" value="Truck" onclick="change(this.value)" />
<input type="button" id="byBtn2" value="Trash" onclick="change(this.value)" />
DEMO
use like this onclick="change(this.value)" .send the value of the input via click function
function change(val) {
if (val.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title');
title.innerHTML = val;
}
There is <span id="title">___________</span> wrong with this world!
<p>
Choose the appropriate word
</p>
<input type="submit" id="myTextField" value="something" onclick="change(this.value)" />
<input type="submit" id="byBtn1" value="Truck" onclick="change(this.value)" />
<input type="submit" id="byBtn2" value="Trash" onclick="change(this.value)" />

Buttons must be pressed in a specific order to send the form - jquery

I am trying to make a puzzle game in which the user must press the button in a specific order in which they fill a textbox (will be hidden) with a password ( 3-digits) if the user pressed the buttons for example ( 3,2,1 ) the form will be submitted automatically and redirecting to another page..
I tried, but I couldn't do it
here are my codes :
<form method="POST">
<input type="text" value="" id="text1" name="text1" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="1" />
<input type="button" value="Click Me" id="2" />
<input type="button" value="Click Me" id="3" />
</form>
jquery
$(function () {
$('#1').click(function(e) {
var text = $('#text1');
text.val(text.val() + '1');
$('#1').attr("disabled", true);
});
$('#2').click(function(e) {
var text = $('#text1');
text.val(text.val() + '2');
$('#2').attr("disabled", true);
});
$('#3').click(function(e) {
var text = $('#text1');
text.val(text.val() + '3');
$('#3').attr("disabled", true);
});
});
$('#text1').trigger('change') {
alert('Changed');
});
you can do something like this: foreach click on an answer button disabele the current button update the input value..and once the user clicks all answers button check if the combination is correct, if it is the case redirect your page.
$(function () {
var correct_order="321";
var clicks=0;
var max_clicks=$('.answer').length;
$('.answer').click(function(e) {
clicks++;
$('#text1').val($('#text1').val()+$(this).data('info'));
$(this).attr("disabled", true);
if(clicks==max_clicks){
if( $('#text1').val()==correct_order) {
$('#answer_info').html("<p>Correct answer</p>");
window.location.href = "https://yourpage";
}
else {
$('#answer_info').html("<p>Wrong answer</p>");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<form method="POST">
<input type="text" value="" id="text1" name="text1" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="1" class="answer" data-info="1"/>
<input type="button" value="Click Me" id="2" class="answer" data-info="2"/>
<input type="button" value="Click Me" id="3" class="answer" data-info="3"/>
</form>
<div id="answer_info">
</div>
It works if you delete the last piece of code
$('#text1').trigger('change') {
alert('Changed');
});
I think the best way is to use a String variable instead of a text input, and check its value after each button is clicked, e.g.
var string = "";
$('#1').click(function(e) {
var = var + "1";
$('#1').attr("disabled", true);
checkCode();
});
$('#2').click(function(e) {
var = var + "2";
$('#2').attr("disabled", true);
checkCode();
});
$('#3').click(function(e) {
var = var + "3";
$('#3').attr("disabled", true);
checkCode();
});
I'm not a 100% sure this works correctly or if it causes an error on:
$(text1).val($(text1)+$(this).id); // might cause an error
code:
$(document).on('click','#1',function()){
$(text1).val($(text1)+$(this).id);
}
$(document).on('click','#2',function()){
$(text1).val($(text1)+$(this).id);
}
$(document).on('click','#3',function()){
$(text1).val($(text1)+$(this).id);
}
$(document).on('change','#text1'){
alert('Changed to: '+$(this).val());
});
Can you try this, and see if this works?

Toggle sub-category divs based on radio button selection

I used the top answer to this question to build a form that feeds into a sheet along with file upload. Now I've hit another wall.
I have categories, and sub-categories. I'd like the sub-categories to only show up IF their parent category has been selected. I just can't figure out A) where I need to put the code (on our website it's right in with the HTML), I've tried putting it in the HTML file and the Code.gs file, or B) if the code I'm using is even right.
Here's the form - the "Co-Op Category" is the parent categories, I have hidden divs for each category that would hold the 'child categories'
HTML:
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
}
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name: <input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br>
Other: <input type="text" name="split" /><br />
Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
Co-Op Category:<br />
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit"
onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
Code.gs:
var submissionSSKey = '1zzRQwgXb0EN-gkCtpMHvMTGyhqrx1idXFXmvhj4MLsk';
var folderId = "0B2bXWWj3Z_tzTnNOSFRuVFk2bnc";
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Form.html');
template.action = ScriptApp.getService().getUrl();
return template.evaluate();
}
function processForm(theForm) {
var fileBlob = theForm.myFile;
var folder = DriveApp.getFolderById(folderId);
var doc = folder.createFile(fileBlob);
// Fill in response template
var template = HtmlService.createTemplateFromFile('Thanks.html');
var name = template.name = theForm.name;
var amount = template.amount = theForm.amount;
var split = template.split = theForm.split;
var reason = template.reason = theForm.split;
var brand = template.brand = theForm.brand;
var category = template.category = theForm.category;
var message = template.message = theForm.message;
var email = template.email = theForm.email;
var fileUrl = template.fileUrl = doc.getUrl();
// Record submission in spreadsheet
var sheet = SpreadsheetApp.openById(submissionSSKey).getSheets()[0];
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 9).setValues([[name,amount,split,reason,category,brand,message,email,fileUrl]]);
// Return HTML text for display in page.
return template.evaluate().getContent();
}
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
This bit specifically is where I'm having trouble:
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
The unexpected token is due to the function(){ line, which is invalid syntax for the jQuery document ready function. You should have:
$(function(){
$('input[type="radio"]').click(function(){
...
});
});
With that fixed, your next error will be:
Uncaught ReferenceError: $ is not defined
That's because you haven't included jQuery, which is what the $ symbol is referring to in statements like $(this). You'll want to read this for more tips about using jQuery in Google Apps Script. The short story, though: You need to add the following, adjusted for whatever version of jQuery you intend to use:
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Updated Form.html, which shows the appropriate <div> as you intended. It also includes the recommended doctype, html, head and body tags:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
}
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//Toggle Secondary Categories
$(function() {
$('input[type="radio"]').click(function() {
if ($(this).attr("id") == "dealer") {
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if ($(this).attr("id") == "online") {
$(".box").not(".online").hide();
$(".online").show();
}
if ($(this).attr("id") == "advertising") {
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if ($(this).attr("id") == "pricing") {
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if ($(this).attr("id") == "correspondence") {
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if ($(this).attr("id") == "meetings") {
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if ($(this).attr("id") == "other") {
$(".box").not(".other").hide();
$(".other").show();
}
});
});
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name:
<input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br> Other: <input type="text" name="split" /><br /> Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
Co-Op Category:<br />
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit" onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
</body>
</html>

How to count the number of selected elements?

I have a lot of elements which are used identical class-name. Now I need to calculate the number of selected items.
For e.g. something like this: (however this example doesn't work correctly)
$("#btn").click(function(){
if($(".necessarily").val() == ''){
$(".necessarily").css('border','1px solid red');
}
// also I want the number of input.necessarily which are empty
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" /><br><br>
<input name="last-name" class="necessarily" type="text" /><br><br>
<input name="email" class="necessarily" type="email" /><br><br>
<input name="password" class="necessarily" type="password" /><br><br>
<input name="address" class="anything" type="text" /><br><br>
<input name="btn" id="btn" type="submit" value="Register" />
</form>
Now I want the number of those inputs which are empty ..., How can I calculate that?
.val() method returns .value property of the first element in the collection. You can filter the empty inputs using the .filter() method and read the .length property of the filtered collection:
var $empty = $(".necessarily").filter(function() {
// you can use the `$.trim` method for trimming whitespaces
// return $.trim(this.value).length === 0;
return this.value.length === 0;
});
if ( $empty.length > 0 ) {
}
If you want to add a border to the empty fields you can declare a CSS class and use the .removeClass and .addClass methods:
CSS:
.red_border {
border: 1px solid red;
}
JavaScript:
var $empty = $(".necessarily").removeClass('red_border').filter(function() {
return this.value.length === 0;
}).addClass('red_border');
You'd do better looking at the HTML5 Contraint API rather than doing what you're currently doing, which is a more manual and time-consuming way.
Instead of giving each field a class 'necessarily' (sidenote: the word you need is 'necessary', not 'necessarily', or, better still, 'required') use the required attribute. So:
<input name="last-name" required type="text" />
Then in your jQuery you can target empty fields with:
$('input:invalid').css('border', 'solid 1px red');
If all you're doing is highlighting bad fields, you don't even need JavaScript for this. You can do the same thing via CSS:
input:invalid { border: solid 1px red; }
The only problem with that is the styling will be showed even before the user has filled out the form, which is almost never desirable. You could get round this by logging, via JS, when the form is submitted, and only then activating the styles:
JS:
$('form').on('submit', function() { $(this).addClass('show-errors'); });
CSS:
.show-errors input:invalid { border: solid 1px red; }
Try this code:
$("#btn").click(function(){
var selectedcount = $(".necessarily").length; //no. of elements with necessarily class name
var emptyInputCount=0;
$(".necessarily").each(function(){
if($(this).val() == ''){
emptyInputCount++;
}
});
Try with each loop on the target elements.
$(function() {
$("#btn").click(function() {
var i = 0;
$(".necessarily").each(function() {
if ($(this).val() == "") {
$(this).css('border', '1px solid red');
i++;
}
});
alert(i); //Number of input element with no value
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" />
<br>
<br>
<input name="last-name" class="necessarily" type="text" />
<br>
<br>
<input name="email" class="necessarily" type="email" />
<br>
<br>
<input name="password" class="necessarily" type="password" />
<br>
<br>
<input name="address" class="anything" type="text" />
<br>
<br>
<input name="btn" id="btn" type="submit" value="Register" />
</form>
Hope this helps!
You can use filter() like following example bellow.
var empty_inputs = $('.necessarily').filter(function(){
return $(this).val()=='';
});
empty_inputs.length will return 3 in my example.
Hope this helps.
var empty_inputs = $('.necessarily').filter(function(){
return $(this).val()=='';
});
console.log(empty_inputs.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="first-name" class="necessarily" type="text" /><br><br>
<input name="last-name" class="necessarily" type="text" /><br><br>
<input name="email" class="necessarily" type="email" value="Register"/><br><br>
<input name="password" class="necessarily" type="password" /><br><br>
<input name="address" class="anything" type="text" value="Register"/><br><br>
<input name="btn" id="btn" type="submit" value="Register" />
Hope this helps.
You need to:
query all elements by className
filter the jQuery Collection in order to keep only the elements that have no value
doSomethingElse
so, this maybe could help you:
function CheckEmptyCtrl($) {
'use strict';
var self = this;
self.target = $('.necessarily');
self.empty = self.target.filter(function(index, item) {
return !($(item).val().trim());
});
$('#result').append(self.empty.length + ' elements have no values.');
console.log(self.empty.length, self.empty);
}
jQuery(document).ready(CheckEmptyCtrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="result"></div>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" value="notEmpty" /><br><br>
<input name="last-name" class="necessarily" type="text" /><br><br>
<input name="email" class="necessarily" type="email" /><br><br>
<input name="password" class="necessarily" type="password" /><br><br>
<input name="address" class="anything" type="text" /><br><br>
<input name="btn" id="btn" type="submit" value="Register" />
</form>
You need to loop over the all of the inputs and count how many are empty. In the same loop you can also count the number of .necessarily inputs which are empty.
This example will output the result to the .result span.
$("#btn").click(function() {
var inputs = $("form input");
var emptyNecessarilyCount = 0;
var totalEmpty = 0
inputs.each(function() {
if ($(this).val() == "") {
totalEmpty++;
if ($(this).hasClass('necessarily')) {
emptyNecessarilyCount++;
}
}
});
$('.result').append("Total: " + totalEmpty);
$('.result2').append("Necessarily: " + emptyNecessarilyCount);
});
span {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" />
<br>
<input name="last-name" class="necessarily" type="text" />
<br>
<input name="email" class="necessarily" type="email" />
<br>
<input name="password" class="necessarily" type="password" />
<br>
<input name="address" class="anything" type="text" />
<br>
<input name="btn" id="btn" type="submit" value="Register" />
<span class="result"></span>
<span class="result2"></span>
</form>

Categories

Resources