I can't use val()? - javascript

I'm having a problem with getting the val of an input element I have.
You see, I don't know if my code is wrong, but my Visual Studio (legal) doesn't even try to help me complete what I want to type. All it gives me is Value() and ValueOf().
The part of the code I'm using:
JS:
$(document).ready(start);
{
$("#b1").click(toev);
}
function toev() {
var value = $("#b1").val();
$("#output").append(value);
};
HTML:
<input type="text" id="output"/>
<td><input type="button" id="b1" value="1" /></td>

Demo http://jsfiddle.net/yS8tw/
Few things to note:
Use of document.ready
Use of Val
Also I like this appendVal function: http://jsfiddle.net/5R7eZ/ - Is it possible to do ".value +=" in JQuery?
Rest should fit the needs :)
code
$(document).ready(function(){
$("#b1").click(toev);
});
function toev() {
var value = $("#b1").val();
alert(value);
$("#output").val(value);
}
With AppendVal
$(document).ready(function(){
$("#b1").click(toev);
});
function toev() {
var value = $("#b1").val();
$("#output").appendVal(value);
}
$.fn.appendVal = function (newPart) {
return this.each(function(){ this.value += newPart; });
};

You can't append content to an <input> element because it cannot have content. Perhaps you meant
$('#output').val(value);
to set its value.

Related

Jquery Not working to create new Inputs

Below is my Html Doc and the JQuery does not do anything when the range input changes, any assistance is much appreciated as I am extremely new to web design. Even the alert doesn't work at the top so I am unsure as to what my problem is. My belief is somehow the script is never being called or it's a problem with it being an html doc but either way thank you.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var num=0;
var numOptions = new Array(100);
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
$(document).ready(function(){
$("#numQuestions").on('input',function(){
var numbQuestions = $("#numQuestions".text());
if(num>numbQuestions){
for(i=numbQuestions;i<=num;i++){
try{
$("#qRowNum'+i).remove();
}catch(err){
}
}
}else{
for ( i=num; i < numbQuestions; i++)
{
var row = '<div id="qRowNum'+ i '">
#the below function is not implemented in this version
<input type="text" placeholder="Question '+i'"> <input type="range" name="numOptions'+i'" min="0" max="5" placeholder="Number Of Options" onchange="CreateOptions(this);" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();> </div>';
$("#questionRows").append(row);
//New script test
}
}
num = numbQuestions;
});
});
<div id="questionRows">
</div>
<input type="submit" value="Start">
</form>
</body>
</html>
This is your problem:
var numbQuestions = $("#numQuestions".text());
Firstly I think you mean this:
var numbQuestions = $("#numQuestions").text();
But that is also not true because an input field has not text property. They have value So do this:
var numbQuestions = $("#numQuestions").val();
And this is another problem: $("#qRowNum'+i) When you start selector by double quotation, you need to end this also by double quotation. But it still is not a true jquery selector.
I think you need to more studies about jquery.

Javascript - prevent onclick event from being attached to all elements with same class

I'm working on a simple form that includes an input field where the user will fill in the required amount by clicking the incrementor/decrementor. The form is created based on data pulled dynamically from the database
Below is the problematic part: html and the jquery handling it:
The incrementor, decrementor and the input field:
-
<input type="text" id="purchase_quantity" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
and the jquery handling the above:
jQuery(function ($) {
$('.addItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num++;
if(num>6)num=6;
console.log(num);
$(".purchase_quantity").val(num);
return false;
});
$('.removeItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num--;
if(num<1)num=1;
console.log(num);
$(".purchase_quantity").val(num);
return false;
});
});
Now, what's happening is: onclick of the incrementor/decrementor (+ and -) the value on the input field changes across all the fields in the page instead of the one clicked only. Have spent quite some time on this with no success and will appreciate some help
The line
$(".purchase_quantity").val(num);
says, literally, to change the value on all the fields. Earlier you used
$(this).siblings('.purchase_quantity').val()
to get the value, so why not also use
$(this).siblings('.purchase_quantity').val(num)
to set it?
That's because siblings will get you all items on the same level.
Get the siblings of each element in the set of matched elements,
optionally filtered by a selector.
Place them in separate div elements, and adjust your setter to actually only update the siblings inside that div.
jQuery(function ($) {
$('.addItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num++;
if(num>6)num=6;
console.log(num);
$(this).siblings('.purchase_quantity').val(num);
return false;
});
$('.removeItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num--;
if(num<1)num=1;
console.log(num);
$(this).siblings('.purchase_quantity').val(num);
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
-
<input type="text" id="purchase_quantity2" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
</div>
<div>
-
<input type="text" id="purchase_quantity1" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
</div>
you should change $(".purchase_quantity").val(num) to $("#purchase_quantity").val(num)

JS | Receiving NaN as output when trying to pull content from text input

I'm new to JS and having trouble parseing text input into a calculation function. I must be doing something fundamentally wrong as I know the actual parse method is correct. I've been trying a bunch of different things but am kind of running around in circles at this point. I'm just making a simple celius/farenheit converter. Any help is greatly appreciated!
NOTE I'm trying to use pure JS only
<body>
<h2>Temperature Converter</h2>
<form>
<input id="degrees" type="text" size="5">
<input type="radio" value="celsius" name="one" id="celsius">Celsius
<input type="radio" value="farenheit" name="one" id="farenheit">Farenheit
<button id="equals" type="button">=</button>
<output id="output">
</form>
<script type="text/javascript" src="js/script2.js"></script>
</body>
var val = parseFloat(document.querySelector("#degrees").value);
var output = document.getElementById("output");
window.addEventListener("load", main);
function main() {
// listen for a click on the "equals" button
document.querySelector("#equals").addEventListener(
"click", function(){convert("val");});
}
function convert(val) {
var c = document.getElementById("celsius");
var f = document.getElementById("farenheit");
if (c.checked) {
toFarenheit(val);
console.log("celsius selected");
} else if (f.checked) {
toCelsius(val);
console.log("farenheit selected");
} else {
console.log("Select whether input is in celsius or farenheit.");
}
}
function toCelsius(val) {
output.value = (val - 32) / 1.8;
console.log(output.value);
}
function toFarenheit(val) {
output.value = val * 1.8 + 32;
console.log(output.value);
}
At this point
convert("val");
you give your convert() function the strings "val" to be used for conversion and not the variable. This leads to the NaN value in the computation later on.
You should move the line, where you retrieve the value val to inside the convert() function, so it will get updated upon the click. Currently you read the value just at startup (where it will most probably be empty) and never update it.
function convert() {
var c = document.getElementById("celsius");
var f = document.getElementById("farenheit");
var val = parseFloat(document.querySelector("#degrees").value);
if (c.checked) {
toFarenheit(val);
console.log("celsius selected");
} else if (f.checked) {
toCelsius(val);
console.log("farenheit selected");
} else {
console.log("Select whether input is in celsius or farenheit.");
}
}
Here is error
document.querySelector("#equals").addEventListener(
"click", function(){convert("val");});
Nedd
document.querySelector("#equals").addEventListener(
"click", function(){convert(val);});
Yip the first commenter to your answer was on the nose. You need to update your val variable on click. You can declare it up top and then update it in the function call, or just create it as a scoped variable in the click listener.
Working fiddle: https://jsfiddle.net/6s5nx7dn/

press button and value increases in text box

So when the page loads the text box will contain a stored value. I want the user to press the '+' button and the value in the text box will increase by one. Im guessing this is done with JQuery...Any ideas on where to get started so far I have...
<input type="text" name="BoqTextBox" id="BoqTextBox" value="0" />
<input type="Button" value="+" onclick="AddOne(document.getElementById('BoqTextBox').value)" />
<script>
function Add(data) {
//so the current digit is passed to here, where I need to do some funky code
//where it increments the current digit by one and stores it in BoqTextBox - replacing the old digit.
//Also to note if the text box contains 124.54 for example and + is pressed
//then new value will be 125.54
}
</script>
Any assistance with this would be great.
Thank you
...something like data = data + 1, but then how do I return the value into the text box?
You can use jQuery's val() to fetch and set a value. In this case the code you need could look like this (demo):
<input type="text" name="BoqTextBox" id="BoqTextBox" value="0" />
<input type="Button" id='AddButton' value="+" />
<script>
$('#AddButton').on('click', function () {
var input = $('#BoqTextBox');
input.val(parseFloat(input.val()) + 1);
})
</script>
$('input[type="button"]').on('click', function() { // bind click event to button
$('#BoqTextBox').val(function() { // change input value using callback
return ++parseFloat( this.value, 10); // make value integer and increment 1
})
});
you are callin Addone function inline so that means your function should be AddOne()
try this
function AddOne(obj){
var value=parseFloat(obj) + 1;
$('#BoqTextBox').val(value);
}
$("#buttonId").click(function()
{
var txtBox = $("#boqtextbox");
if(!isNaN(txtBox.val()))
{
txtBox.val(parsFloat(txtBox.val())+1) ;
}else
{
//do validation or set it to 0
txtBox.val(0);
}|
});

Getting DOM element value using pure JavaScript

Is there any difference between these solutions?
Solution 1:
function doSomething(id, value) {
console.log(value);
//...
}
<input id="theId" value="test" onclick="doSomething(this.id, this.value)" />
...and Solution 2:
function doSomething(id) {
var value = document.getElementById(id).value;
console.log(value);
//...
}
<input id="theId" value="test" onclick="doSomething(this.id)" />
Update: The question was edited. Both of the solutions are now equivalent.
Original answer
Yes, most notably! I don't think the second one will work (and if it does, not very portably). The first one should be OK.
// HTML:
<input id="theId" value="test" onclick="doSomething(this)" />
// JavaScript:
function(elem){
var value = elem.value;
var id = elem.id;
...
}
This should also work.
The second function should have:
var value = document.getElementById(id).value;
Then they are basically the same function.
In the second version, you're passing the String returned from this.id. Not the element itself.
So id.value won't give you what you want.
You would need to pass the element with this.
doSomething(this)
then:
function(el){
var value = el.value;
...
}
Note: In some browsers, the second one would work if you did:
window[id].value
because element IDs are a global property, but this is not safe.
It makes the most sense to just pass the element with this instead of fetching it again with its ID.
Pass the object:
doSomething(this)
You can get all data from object:
function(obj){
var value = obj.value;
var id = obj.id;
}
Or pass the id only:
doSomething(this.id)
Get the object and after that value:
function(id){
var value = document.getElementById(id).value;
}
There is no difference if we look on effect - value will be the same. However there is something more...
Solution 3:
function doSomething() {
console.log( theId.value );
}
<input id="theId" value="test" onclick="doSomething()" />
if DOM element has id then you can use it in js directly
This should also work.
function doSomething() {
yourElement = document.getElementById("yourID);
yourValue = yourElement.value; console.log(yourValue);
console.log(yourValue);
}
<div id="yourID" value="1" onclick="doSomething()">
</div>
function doSomething() {
console.log( theId.value );
}
<input id="theId" value="test" onclick="doSomething()" />

Categories

Resources