Why the value of the text input appears undefined? - javascript

I tried to make a text type input named 'pr2__answer', but when I view the value of it using console.log(answer.val()), it appears 'undefined'. I don't know why.
This is part of my code:
var country_capital_pairs = pairs;
var new_pairs = {};
for (var i = 0; i < country_capital_pairs.length; i++) {
new_pairs[country_capital_pairs[i].country] = country_capital_pairs[i].capital;
}
var capital_names = Object.values(new_pairs);
var question = $("#pr2__question");
var answer = $("#pr2__answer");
var len = country_capital_pairs.length;
var Q = country_capital_pairs[Math.floor(Math.random()*len)];
var question_country = Q.country;
question.html(question_country);
answer.autocomplete({
minLength: 2,
source: capital_names,
select: function(evt, ui) {
console.log(ui);
answer.val(ui.item.value);
$("input#pr2__submit").click();
return false;
}
}).focus();
The function answer.autocomplete doesn't work. So I think the problem is that the program doesn't remind that I am typing something in the input. Can anyone tell me why?
And this is a part of my HTML code:
<tr>
<td id="pr2__question"></td>
<td><input type="text" id=pr2__answer" /></td>
<td><input type="submit" id="pr2__submit" value="seeAnswer()" //></td>
</tr>

You need to put your javascript code in the end of your html page or put you code inside of the function :
$( document ).ready(function() {
// your code
});

Related

Getting form element by value in Javascript

Hey guys I have a form which is stated below
<td><input type="text" id="NumberofRisks" name="Yeses" style="width: 25px" value ="<?php echo $row['Total-Score'];?> " </td>
The form has some data from a table as a value and I would like to take this value into my Javascript from to do a simple calculation. The function is listed below.
function sum()
{
sumField = document.getElementById("NumberofRisks");
var sum = 0;
$("input[name^='yanswer']:checked").each(function(){
sum++;
});
sumField.value = sum;
}
I need to get that value into the function as the value where it says NumberofRisks. Is there a way I can do this?
Try this to set sum to the initial value of #NumberofRisks.
var prevCheckedCount = 0;
function sum()
{
var sumField = document.getElementById("NumberofRisks");
// start sum with the inital value in HTML from DB
var valueOnClick = Math.floor(sumField.value);
var thisCheckedCount = 0;
$("input[name^='yanswer']:checked").each(function(){
thisCheckedCount++;
});
if(thisCheckedCount <= prevCheckedCount) {
sumField.value = valueOnClick - prevCheckedCount + thisCheckedCount;
} else {
sumField.value =valueOnClick + thisCheckedCount;
}
prevCheckedCount = thisCheckedCount;
}
Here's this code working: http://jsfiddle.net/t5hG4/
In order to grab the value of the input box you can use the following javascript:
var sum = document.getElementById("NumberofRisks").value;
Is this what you're trying to achieve?
As a side note, in the example you provided you did not close the input box so that might be giving you some errors as well.
EDIT:
If you're looking for a pure Javascript way to do this see below:
var elements = document.getElementsByTagName('input');
var sum = document.getElementById("NumberofRisks").value;
for (var i = 0; i < elements.length; i++) {
if (elements[i].checked) {
sum++
}
}
See fiddle - http://jsfiddle.net/es26j/

entry in input one by one should show added result in result field

when user select any option in radio buttons in group one and then enter any number in respective input field and then select the next any radio option and enter any value in input field then this time it should add the new result with old one and display it in result input field and now if he empty any input field then that should also minus from the total result and display it in result field.
i have so many groups like that but here i just put two of them to get the result.
here id the FIDDLE
here is the jquery code. i can work in jquery but not very good i used separate code for every group and i know there must be a way to get this whole functionality through generic code but again i am not good at jquery
jQuery("#txt_im").keyup(setValue);
jQuery('[name="rdbtn-im"]').change(setValue);
function setValue() {
var txt_value = jQuery("#txt_im").val();
var rad_val = jQuery('[name="rdbtn-im"]:checked').val();
if(!txt_value.length) {
jQuery('#final_res').val('');
return;
}
if (!rad_val.length) return;
var res = txt_value * rad_val;
var final = parseInt(res, 10);
var MBresult = final / 1024;
jQuery('#final_res').val(MBresult.toFixed(2));
}
var final2 = 0;
jQuery("#txt_fb").keyup(setValue2);
jQuery('[name="rdbtn-fb"]').change(setValue2);
function setValue2() {
var txt_value = jQuery("#txt_fb").val();
var rad_val = jQuery('[name="rdbtn-fb"]:checked').val();
if(!txt_value.length) {
jQuery('#final_res').val('');
return;
}
if (!rad_val.length) return;
var res2 = txt_value * rad_val;
final2 = parseInt(res2, 10) + final;
var MBresult = final2 / 1024;
jQuery('#final_res').val(MBresult.toFixed(2));
}
infact user is free to select any number of groups or also free to remove any number of group after selection.
i know there is error in fiddle when user select 2nd group after the select of first it removes the result which is wron and i tried to solve it but failed but i define the whole seen what i need to do. i will be very thankfull to you for this kind favour.
HTML:
<table>
<tr>
<td>
<input type="radio" name="rdbtn-im" id="rdbtn-im-day" value="25" class="rdbtn-style-social" />Daily
<input type="radio" name="rdbtn-im" id="rdbtn-im-week" value="175" class="rdbtn-style-social" />Weekly
<input type="text" name="txb3" id="txt_im" class="txt-email" style="width:100px;margin: 2px;" />
</td>
</tr>
<tr>
<td class="sec-td-rdbtns-social">
<input type="radio" name="rdbtn-fb" id="rdbtn-fb-day" value="3500" class="rdbtn-style-social" />Daily
<input type="radio" name="rdbtn-fb" id="rdbtn-fb-week" value="500" class="rdbtn-style-social" />Weekly
<input type="text" name="txb1" id="txt_fb" class="txt-email" style="width:100px;margin: 2px;" /> </td>
</tr>
</table>
<br>result
<input type="text" name="final_res" id="final_res" class="" style="width:100px;margin: 2px;" />
Jquery:
jQuery(".txt-email").keyup(setValue);
jQuery('.rdbtn-style-social').change(setValue);
function setValue() {
var total = 0;
$(".rdbtn-style-social:checked").each(function () {
var myInput = $(this).siblings(".txt-email").val();
if (myInput.length) {
total += myInput * $(this).val();
}
});
if (total) {
jQuery('#final_res').val((total / 1024).toFixed(2));
} else {
jQuery('#final_res').val('');
}
}
FIDDLE
If you are using chrome, then console is your best friend ( https://developers.google.com/chrome-developer-tools/docs/console )
For firefox you have firebug, opera has dragonfly (or something like that ?). Even IE has console now. There you can see all errors popping up.
Ok, so first of all let's clean up this a little bit by wrapping it all in closure (we can now safely use the $ instead of jQuery even if there is namespace conflict outside). Also, we will use single function for both cases, because they are so similar.
!function ($) {
$(".txt-email").keyup(setValue);
$('.rdbtn-style-social').change(function(e) { setValue(e, true) });
function setValue(e, radio) {
if('undefined' === typeof radio) radio = false;
var attr = radio ? 'name' : 'id';
var tmp = e.target[attr].split('-');
var media = tmp[tmp.length - 1];
var txt_value = $("#txt-"+media).val();
var rad_val = $('.rdbtn-style-social[name="rdbtn-'+media+'"]:checked').val();
if (!txt_value.length || !rad_val.length) {
$('#final_res').val('');
return false;
}
var res = (txt_value | 0) * rad_val;
var final = parseInt(res, 10);
var MBresult = final / 1024;
$('#final_res').val(MBresult.toFixed(2));
}
}(jQuery);
(variable | 0 is same as parseInt(variable, 10)).
So, long story short: when radio or text gets changed, the function is fired (if it's radio, additional argument is passed). We retrieve whether we want to work on im or fb, then do whatever you want. I changed id of inputs to replace _ with -'s (for split consistency)
Final jsfiddle: http://jsfiddle.net/Misiur/f6cxA/1/

Javascript - use class name to specify which variable to assign value to

I'm trying to be clever with some efficient Javascript but it's causing me headaches and lots of fruitless searching.
I have a set of inputs in a table, each with a given class:
...
<tr>
<td><input name="name" type="text" class="markertitle"/></td>
<td><input name="desc" type="text" class="markerdescription"/></td>
<td><input name="address" type="text" class="markeraddress"/></td>
<td><input name="url" type="text" class="markerurl"/></td>
</tr>
...
I want to take the value of those classes, use it to specify a given variable (which already exists), then assign the value of the input (using +=) to that variable.
This is what I've come up with, but no joy:
var markertitle = {};
var markerdescription = {};
var markeraddress = {};
var markerurl = {};
$('#markermatrixadd input').each(function(){
var field = $(this).attr('class');
window[field] += $(this).val() + ',';
});
It's dead simple I'm sure, but I think my brain's a bit fried :(
Your vars don't seem to be global. They must be declared outside any function. Besides that, you cannot add anything to an object ({}). Use either strings or arrays:
var markertitle = ""
var markerdescription = ""
etc
function() ....
$('#markermatrixadd input').each(function(){
var field = $(this).attr('class');
window[field] += $(this).val() + ',';
});
or
var markertitle = []
var markerdescription = []
etc
function() ....
$('#markermatrixadd input').each(function(){
var field = $(this).attr('class');
window[field].push($(this).val())
});
Better yet, get rid of window and use one single object to store all the data:
var data = {
markertitle: "",
markerdescription: ""
}
function() ....
$('#markermatrixadd input').each(function(){
var field = $(this).attr('class');
data[field] += $(this).val() + ',';
});

trying to get values from a HTML form?

I have a HTML form where i dynamically create elements and set its name , value attributes .
when i tried to access the value say document .formname.nameoftheelement.value then i get the error that value is undefined.
Then i tried to use the following function to access the values .it returns the input elements as 4 but value as null when i it already has predefined value .
function returnTheStoredValues(getTableName) {
//Array arrList = new Array(20);
var tableName = document.getElementById (getTableName);
console.log("The table name" + tableName);
if (tableName) {
var inputs = tableName.getElementsByTagName ('td');
console.log("the inputs are " + inputs.length);
if (inputs) {
console.log("inputs not equal to null")
for (var i = 0; i < inputs.length; ++i) {
console.log("the value in phones table are " + inputs[i].value);
//arrList[i] = inputs[i].value;
}
}
}
//return arrList;
}
The html code is
Phone
<table id="email_table">
<tr>
<td><h3>Email</h3></td>
<td><input value="+" type="submit" onClick="checkTheEmailButtonClicked()"></td>
</tr>
</table>
<table>
<tbody>
<tr>
<td><input type="submit" value ="Save" onclick="getData();"/></td>
<td><input type="submit" value = "Cancel"/></td>
</tr>
</tbody>
</table>
Appreciate all your help .
You seem to want the values of the input elements, so:
function returnTheStoredValues(getTableName) {
var arrList = [];
var table = document.getElementById(getTableName);
var inputs = table.getElementsByTagName('input');
for (var i=0, iLen=inputs.length; i<iLen; i++) {
arrList[i] = inputs[i].value;
}
return arrList;
}
Because you're getting the TD's and not the INPUT's?
var inputs = tableName.getElementsByTagName('td');
Should be
var inputs = tableName.getElementsByTagName('input');
By the way, if you use a Javascript framework, your code will be happier.
You really need to look into using jQuery for accessing elements through JavaScript.
You could then re-write your function to the following:
function returnTheStoredValues(getTableName) {
return $("#email_table input").map(function() {
return $(this).val();
}).get();
}

Change value of form boxes with jQuery onBlur

I'm looking to write a jQuery function that will change the value of other input boxes when an onBlur event occurs. In the code below, I'm attempting to read in the value of the input box that has been altered and use its value to manipulate the value of the other input boxes. Eventually, this will be used as a conversion utility. I feel like I'm pretty close here, can someone help?
Thanks!
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js">
<script type="text/javascript">
$('#a').bind('blur', function() {
var a = $('#a').val();
var b = a*1;
var c = a*1;
$('#b').val(b);
$('#c').val(c);
});
$('#b').bind('blur', function() {
var b = $('#b').val();
var a = b*2;
var c = b*2;
$('#a').val(b);
$('#c').val(c);
});
$('#c').bind('blur', function() {
var c = $('#c').val();
var a = c*3;
var b = c*3;
$('#a').val(a);
$('#b').val(b);
});
</script>
<div style="width:500px">
<table width="500">
<tr>
<td><input type="text" id="a" value="1"/></td>
<td><input type="text" id="b" value="1"/></td>
<td><input type="text" id="c" value="1"/></td>
</tr>
</table>
</div>
Change
$('#a').val(b);
to
$('#a').val(a);
in second bind.
i found your error:
change this:
$('#b').bind('blur', function() {
var b = $('#b').val();
var a = b*2;
var c = b*2;
$('#a').val(b);
$('#c').val(c);
});
to this:
$('#b').bind('blur', function() {
var b = $('#b').val();
var a = b*2;
var c = b*2;
$('#a').val(a);
$('#c').val(c);
});
you accidentally gave $('#a').val = b when there is no b
see answer working fully here:
http://jsfiddle.net/Ru6FV/
You would probably want to fire whole javascript after html is loaded correctly:
$(function() {
$('#a').bind(...
...
});
});
What exactly is the issue? It seems to work somehow (didn't check for the calculations)... implementation with jsfiddle
You are missing the </script> tag after loading jquery.

Categories