jQuery: Count Number of Inputs with a Specific Value - javascript

I need to count the number of text inputs with a value of 1.
I have tried the following but with no luck.
$('.class[value="1"]').length
$('.class:contains("1")').length
Using $('.class[value="1"]') technically works, however, if the values in the text input are changed after load, it still counts it as its default load value.
I took a long shot by using the .live click event to get the current value but still no luck.
I had no luck at all using $('.class:contains("1")')
It seems very simple, but has so far eluded me.

This example demonstrates that this works:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#btn").click(function() {
alert($(":input[value='1']").length);
});
});
</script>
</head>
<body>
<input type="text">
<input type="text">
<input type="text">
<input type="button" id="btn" value="How many?">
</body>
</html>
Alternatively you can just loop:
var matches = 0;
$(":input.class").each(function(i, val) {
if ($(this).val() == '1') {
matches++;
}
});

You need to iterate with $.each() if you want current val() values:
k=0;
$('.class').each(function(i, e) {
if ($(e).val() == "1") k++;
});

$(':input.class').filter(function() {
return $(this).val() == '1'
})

Related

populate a HTML select in form using Javascript

I have a problem by populating a HTML select.
This select is in an form that first is loaded into a div. (see the code below)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" />
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function createForm(){
$("#formdiv").load("Register.html");
var itemval= '<option value="OT">OT</option>';
document.getElementById("sel").appendChild(itemval);
}
function validateForm(){
// ...
}
</script>
</head>
<body onload="createForm()">
<div id="formdiv" >
// here will be the form
</div>
</body>
The Register.html is a simple form
<h2>Register</h2>
<form name="registerForm" id="registerForm" onsubmit="validateForm()">
Select:<select name="sel" id="sel"></select>
<input type="submit" value="Submit">
</form>
The function createForm() should populate, here as a first test, the select tags. But unfortunately it does not show any option in the browser.
Hope some of you are more experienced than I and can hint me to the solution.
Thanks in advance!
Here the problem is that you use appendChild with a String,
you should use innerHTML to insert a string, or of you want to append
do createElement and then append, appendChild accepts Node as a parameter,
in your case its better use add() method on select
http://www.w3schools.com/jsref/met_select_add.asp
<script type="text/javascript">
function createForm() {
var option = document.createElement("option");
option.text = "OT";
option.value = "OT";
document.getElementById("sel").add(option);
}
function validateForm() {
// ...
}
</script>
<div id="formdiv">
<form name="registerForm" id="registerForm" onsubmit="validateForm()">
Select:
<select name="sel" id="sel"></select>
<input type="submit" value="Submit">
</form>
</div>
<h2>Register</h2>
See jsfiffle link: http://jsfiddle.net/qgfbhgwd/
with a working example
You have 2 mistakes:
Use jQuery load function because is async so you are creating the content before loading the file register.html
appendChild needs a DOM Element instead of a string
This code fix your problem, hope it helps:
function createForm(){
var populateSelect = function() {
var itemsValues = ['OT', 'FOO', 'BAR'];
var items = document.createDocumentFragment();
itemsValues.forEach(function(el) {
var option = document.createElement("option");
option.value = el;
option.innerHTML = el;
items.appendChild(option);
});
document.getElementById("sel").appendChild(items);
};
$("#formdiv").load("register.html", populateSelect);
}
You can't add <option value="OT">OT</option> directly as appendChild, so use javascript createElement and always better to write a callback function for jquery load() to manipulate DOM.
function createForm() {
$("#formdiv").load("Register.html", function () {
//var itemval = '<option value="OT">OT</option>';
var itemval = document.createElement("option");
itemval.setAttribute("value", "OT");
itemval.innerText = "OT";
document.getElementById("sel").appendChild(itemval);
});
}

Dynamically Add and Remove HTML Elements not working

I need to dynamically add and remove HTML elements to my product form (attribute addition purpose) and was searching stack overflow.
I found this solution to be very close (except it does not has a remove option plus I sincerely do not know how to retrieve the data of each textbox, but all this later).
https://jsfiddle.net/nzYAW/
The code in the fiddle works fine. But as I tried it on my local machine it fails to produce any result.
Here is what I did
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
.extraPersonTemplate {display:none;}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).appendTo('#container');
$('#addRow').click(function () {
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).hide().appendTo('#container').slideDown('slow');
});
})
function GetHtml() {
var len = $('.extraPerson').length;
var $html = $('.extraPersonTemplate').clone();
$html.find('[name=firstname]')[0].name = "firstname" + len;
$html.find('[name=lastname]')[0].name = "lastname" + len;
$html.find('[name=gender]')[0].name = "gender" + len;
return $html.html();
}
</script>
</head>
<body>
<div class="extraPersonTemplate">
<div class="controls controls-row">
<input class="span3" placeholder="First Name" type="text" name="firstname">
<input class="span3" placeholder="Last Name" type="text" name="lastname">
<select class="span2" name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
</div>
<div id="container"></div>
<i class="icon-plus-sign icon-white"></i> Add another family member</p>
</body>
</html>
and this is the result
Where did I go wrong at copy paste?
You need to load jQuery library
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to include jQuery. If you check your javascript console (which you definetly should) you will probably find this error:
$ is not defined
That is because jQuery wasn't loaded before you try to use it. Add this to your page before your javascript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can see in the JSFiddle that you include these libraries, but you don't include them when you just copy paste this.
Include these javascripts
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
Move the JavaScript to be right above the </body> tag.
I think if you're trying to access elements before the page has loaded them, then it won't work.
Also as other answers have pointed out, be sure you've included jQuery in the <head></head> section of your page.

jquery selectors, what is wrong with my code?

What i want to do is that when i click on the button "1" it should display the number "1" in the textbox above it.
what is wrong with my jquery code?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JQuery Tutorial</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<input id="textbox" type="text" />
<div>
<input id="1" type="button" value="1" />
<input id="2" type="button" value="2" />
<input id="3" type="button" value="3" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script type="text/javascript" src="js/ext.js"></script>
</body>
My jquery
$('#1').click(function)({
var txt = $('#textbox');
$('#1').html('txt');
});
Try this code
$('input[type="button"]').click(function() {
var txt = $(this).val();
$('#textbox').val(txt);
});
Will explain your problem with your jQuery code:
Line 1:
You registered with #1 button so this will be triggered on when button 1 is click, I made it generalised
Line 2:
You are getting value from textbox, whereas you are supposed to take value from button text.
Line 3:
You are assigning value in button, whereas you are supposed to assign to textbox and always use val() for input type of control and html() for other html container controls
The above were your errors explained.
Queries welcomed!
Fiddle demo
$(function(){
$('input[type="button"]').click(function(){
$('#textbox').val($(this).val());
});
});
You have to get the value using val() method. Also, you are passing variable txt as string to the html() function which is wrong. Try the below...
var txt = $('#textbox').val();
$('#input1').html(txt);
Try this
$('input[type="button"]').click(function() {
$('#textbox').val($(this).val());
});
You can try this one
$('div').on('click', 'input', function () {
$('#textbox').val(this.value);
});

HTML Form Questions / Console Log

console.log(value); does not log anything but the number on the left is incrimented everyime i click and it indicates that the console.log() call is made, just not showing what I put into it.
Also, a side question is how could I do this if the javascript is in a different file? Thank you
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Star Delete</title>
<!--<script type="text/javascript" src="StarDelete.js"></script>-->
</head>
<body>OKAY DELETE STAR YES ;D!
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="theButton"/>
</form>
<script type ="text/javascript">
var button = document.getElementById("theButton"),
value = button.form.valueId.value;
//value = document.getElementById("formValueId").value;
button.onclick = function() {
console.log(value);
}
</script>
</body>
</html>
http://jsfiddle.net/3wjRJ/1/
var button = document.getElementById("theButton"),
value = button.form.valueId.value;
Here you go, the issue was that you were declaring the value variable when the javascript was first loaded, therefore it was always blank.

Set cursor position in an input text field

After a lot of search I found the following threads:
define cursor position in form input field
jQuery Set Cursor Position in Text Area
Unfortunately in none of the posts a complete form embed code or a real example is given. Now I just don't know how to include nemisj's code (on the first link) or Mark's code (on the second link) into my form:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#site").focus(function(){
if( this.value == this.defaultValue ) {
$(this).val("http://");
}
});
});
</script>
</head>
<body>
<form action="#" method="post">
<input id="name" type="text" name="name" value="Name" /><br />
<input id="site" type="text" name="mail" value="Website" /><br />
<input type="submit" value="Send">
</form>
</body>
</html>
I wonder if someone could kindly help me with this as I'm badly stuck!
Many thanks in advance!
Here's the edited code, but it still doesn't work:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script>
function setCursor(node,pos){
var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
if(!node){
return false;
}else if(node.createTextRange){
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
}else if(node.setSelectionRange){
node.setSelectionRange(pos,pos);
return true;
}
return false;
}
$(document).ready(function(){
$("#site").focus(function(){
if( this.value == this.defaultValue ) {
$(this).val("http://");
var node = $(this).get(0);
setCursor(node,node.value.length);
}
});
});
</script>
</head>
<body>
<form action="#" method="post">
<input id="name" type="text" name="name" value="Name" /><br />
<input id="site" type="text" name="mail" value="Website" /><br />
<input type="submit" value="Send">
</form>
</body>
</html>
Inside your <script></script> tag is where your JavaScript goes (although we prefer putting it in a separate file, so that no JavaScript lives on the HTML page itself).
Inside that, you have a call to $(document).ready(), which passes a function() { ... }. Inside that function is all the code that will be executed when your document has loaded.
Inside that function you have a call to $('#site').focus() which itself provides a function — this time one that will be called whenever the #site element gains focus. And presumably that's where you want to change the cursor position.
So, taking the setCursor function from Set cursor at a length of 14 onfocus of a textbox you can put that anywhere in your <script></script> and then inside that innermost function of yours you can write:
if( this.value == this.defaultValue ) {
$(this).val("http://");
var node = $(this).get(0);
setCursor(node,node.value.length);
}
I think I found the error in your setCursor method. The moveStart and moveEnd methods expect two arguments, the first being the unit it should use. Also, the end position appears to be relative to the start position. So I think instead of
textRange.moveEnd(pos);
textRange.moveStart(pos);
you want
textRange.moveStart('character', pos);
textRange.moveEnd('character', 0);
See: http://msdn.microsoft.com/en-us/library/ie/ms536623(v=vs.85).aspx
Oh, this one's easier done than said!
<script>
function setCursorInputPosition(e, pos) {
e.setSelectionRange(pos, pos);
}
</script>
<input onfocus="setCursorInputPosition(this, this.value.length);">

Categories

Resources