Getting form element by value in Javascript - 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/

Related

Get the selected value in google app script

How to pass a select box value.
I have a spreadsheet where i want to filter based on a select box value.
I made a way to call the app function on form submit. But I am not able to pass one more parameter at the other side.
I want to filter based on the select box value and thereby retrieve the result from the spreadsheet on to the web app. This is my selectbox in html.
Select DATA
<select name ="productId" id="gettheVAL">
<option>DATA1 </option>
<option>DATA2 </option>
<option>DATA3 </option>
</select>
Can anyone guide me on this? I have called the function via this
form.on('submit', function(event){
event.preventDefault();
runner.withSuccessHandler(function(array){
for (var i = 0; i < array.length; i++) {
var item = '<tr><td>' + array[i] +'</td></tr>';
table.append(item);
}
}).retrieveValuesFromForm(this);
Update
Adding the function - retrieveValuesFromForm below:
function retrieveValuesFromForm(req) {
//var selectedvalue=$('input[name="gettheSelectValue"]:checked').val();// tried like this but $ is undefined here
var sheetActive = SpreadsheetApp.openById("SHEETID");
var sheet = sheetActive.getSheetByName("SHEETNAME");
var range = sheet.getRange('A:U');
var rawData = range.getValues();
var data = [];
for (var i = 0; i < rawData.length; i++) {
if ((rawData[i][2] == selectedvalue)) // Check to see if column 3 says selectedvalue if not skip it
{
//processing
}
}
return data;
}
Based on the assumption that you have a field in your form such as
<select name ="productId" id="gettheVAL">
In your form, You could call your Google App Script function with the following parameter
runner.withSuccessHandler(function(array){
...
}).retrieveValuesFromForm($("#gettheVAL").val());
You would then change the signature for retriveValuesFromForm
function retrieveValuesFromForm(selectVal) {
...
}
Here's how I pass a selected option and a few other things.
function sendText()
{
var culr=$('input[name="priority"]:checked').val();
var type=$('#sel1').val();
var txt=$('#txt1').val();
var obj={'type':type,'text':txt,'color':culr};
$('#txt1').css('background-color','#ffff00');
google.script.run
.withSuccessHandler(clearText)
.dispText(obj);
}
I'm guessing that you need to add this line into your head tag area.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Display number of Input fields based on the value in database column

I have a database table with column name qty that holds an int.Now i want to display as many input fields as the value in qty.
So far i haved tried this using iavascript code . Here is my javascript code .
$(function() {
var input = $(<input 'type'="text" />);
var newFields = $('');
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n+1) {
if (n > newFields.length) {
addFields(n);
} else {
removeFields(n);
}
}
});
function addFields(n) {
for (i = newFields.length; i < n; i++) {
var newInput = input.clone();
newFields = newFields.add(newInput);
newInput.appendTo('#newFields');
}
}
function removeFields(n) {
var removeField = newFields.slice(n).remove();
newFields = newFields.not(removeField);
}
});
Just store the value in the textfield(hidden)
HTML:
<input type="hidden" id="quantitycount" value="4" />
<div class="textboxarea"></div>
Jquery:
Get the textbox value
var quantitycount=jQuery('#quantitycount').val();
var txthtml='';
for(var txtcount=0;txtcount<quantitycount;txtcount++){
txthtml+='<input type="text" id="txtbox[]" value="" />';
}
jQuery('.textboxarea').html(txthtml);
You can use entry control loops to loop for number of times
Now we can see number of textbox as per need, Just the value from db and store that in the textbox
You can try this
foreach($qty as $qt){
echo '<input type="text">';
}
To append the text fields you need a wrapper on your html form
use some wrapper as mentioned by #Rajesh: and append your text-fields to that wrapper as shown below
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n >0) {
for(var x=0;x<n;x++){
$('#textboxarea').append('<input type="text" name="mytext[]"/>');
}
});
similarly you can write your own logic to remove the text-fields also using jquery

Replacing a sub-string in JavaScript innerHTML

I have an HTML page which contains table rows like
<tr id="tp1">
<input type="checkbox" id="tc_">
</tr>
<tr id="tp2">
<input type="checkbox" id="tc_">
</tr>
The page contains input elements other than checkboxes as well
I have to change the values of all checkbox's id from tc_ to tc_1 ,tc_2 and so on.
I have thought of doing it as below
function startup(){
for(var i=0;i<3;i++)
{
var elem=document.getElementById("tp"+i);
var str=elem.innerHTML;
str.replace(/tc_,'tc_'+i); // how do I correctly use the arguments here?
elem.innerHTML=str;
//alert (""+str);
}
}
Thanks.
It isn't valid to have non-unique IDs in the first place. Any chance you can fix how the checkboxes are rendered so you don't have to do this?
That being said, I wouldn't do this by manipulating the HTML attributes. I would instead do this by manipulating the DOM properties of those input checkboxes:
// keep track of the current "new" checkbox ID suffix
var checkBoxIndex = 0;
for (var i = 0; i < 3; i++) {
// find the table row
var elem = document.getElementById("tp" + i);
// get the input elements within that row
var inputs = elem.getElementsByTagName("input");
// for each of the input elements...
for (var j = 0, k = inputs.length; j < k; j++) {
// if it's not a checkbox, skip it
if (inputs[j].type.toLowerCase() !== 'checkbox') {
continue;
}
// Alas, give the checkbox a new, unique ID
inputs[j].id = "tc_" + (checkBoxIndex++);
}
}
Also, hopefully you get an answer for your other question. This is a terrible workaround and I would hate to see it in production code.
The trick here is to select all the input elements of your rows using the appropriate CSS selector, then modify their ids:
function startup() {
for (var i = 0; i < 3;i++) {
var elem = document.getElementById("tp" + i);
var l = elem.querySelectorAll('td > input'); // Select "input"s in "td"s
Array.prototype.forEach.call(l, function (e, j) { // Apply to each element obtained
e.id = 'tc_' + j; // Modify the id
});
}
}
There's several good answers above but if you still want to change the id from tc_ to tc_ + i then you can do it like this.
<body>
<button id="tc_">1</button>
<button id="tc_">2</button>
<button id="tc_">3</button>
<script type="text/javascript">
for(var i=0;i<3;i++)
{
document.getElementById("tc_").id="tc_"+i;
}
</script>
</body>
Honestly though you shouldn't be doing it like this despite the fact this code works as other users have said it isn't valid to have non-unique id's.

dynamic arrays with input javascript

I am currently doing a school project where I have to use javascript to create a page where a user can key in multiple numbers from an input box.
After each number is entered there is a add button which then shows the number in another box below the input. So each number is displayed vertically down the page.
From there I need two more buttons. The first one to calculate which will add the numbers together and work out the average. The second one will clear the array to start again.
I believe I am ok with the last two buttons. What I am unsure of is how should the user input create the dynamic array which will then be displayed in the page. I have been able to get a single number input but I am missing the next step so the next number entered will dispay and allow me to build an array from which the calculations can be performed.
Please try this I think it will work for you
JAVA SCRIPT :
<script type="text/javascript">
var arr = new Array();
function addNum()
{
var temp = document.getElementById('a').value;
arr.push(temp);
document.getElementById('a').value = "";
getAvg();
}
function getAvg()
{
var sum = 0;
for(var i = 0; i < arr.length; i++){
sum += parseInt(arr[i]);
}
var avg = sum/arr.length;
document.getElementById('sum').value = sum;
document.getElementById('avg').value = avg;
}
function clearAll()
{
arr.length = 0;
document.getElementById('a').value = "";
document.getElementById('sum').value = "";
document.getElementById('avg').value = "";
}
</script>
HTML:
<table>
<tr><td><input type="text" id="a"></td>
<td>Sum :<input type="text" id="sum"></td>
<td>Avg :<input type="text" id="avg"></td></tr>
<tr><td><input type="button" value="add" onclick="addNum()"></td>
<td><input type="reset" value="reset" onclick="clearAll()"></td></tr>
</table
Easiest way would be to loop over the inputs showing the numbers and add each number that way, rather than trying to maintain an array that is updated from the first input.
Stick the displaying input elements into a container with an id, then you can do something simple like:
var container = document.getElementById("container-id"),
inputs = container.children,
total;
for (var x = 0, y = inputs.length; x < y; x++) {
total += parseInt(inputs[x].value, 10);
}
alert(total) //do something way better than alert!

Javascript for loop to change the name of textareas in a function

I have created 50 textareas with names def1,def2,def3.....,def50. In my body onLoad() function,I want the same value is set in all these textboxes.
Instead of writing the code 50 times, How can I write some Javascript code to set the value of the textarea, ie in a loop?
I suggest to read the MDC JavaScript guide, as loops and string concatenation are fairly basic operations:
for(var i = 1; i < 51; i++) {
var nameOfTextarea = 'def' + i;
// ...
}
I would give your textboxes ID's (not just names) if possible, and then do something like the following:
var namePrefix = "def";
for(var i = 1; i <= 50; ++i)
{
var textbox = getElementById(namePrefix + i);
// do something to textbox number i.
}
Try jquery for this:
<input type="text" id="t1"/>
<input type="text" id="t2"/>
<input type="text" id="t3"/>
The Jquery code:
var arr = [ "t1", "t2", "t3" ];
jQuery.each(arr, function() {
$("#"+this).val("hello");//$("#" + this).text("hello");
});
Here is the working demo
Try this.
var textareas = document.getElementsByTagName("textarea");
for(var i=0;i<textareas.length;i++){
if(textareas[i].id.indexOf("def") == 0){
textareas[i].value = textareas[i].id;
}
}
You can use tagname property but it will not work if you have some more textbox anywhere else in your page
function loader(){
for(var i=0;i<50;i++)
document.getElementsByName("def"+i)[0].value='Any Value';
}

Categories