How to concatenate a JS variable in an HTML script? - javascript

Can I do something like this?
var counter = SomeJSFunctionThatReturnsAvalue();
<tr><td> <input type="file" name="file-upload"+"_counter" id="file-upload" /></tr></td>
Can I do that? I need to append an underscore and an incremented number to the name.
Also, an off-topic question - that function above returns the value of an input type, for example:
<input type="hidden" name="hidden-input-type" value="2" />
Is the value "2" a number that I can use for math operations? If not, how can I make it one?

Here you go fella.
<head>
<script>
function test($count) {
document.getElementById("test1").setAttribute("name","file-upload_" + $count);
}
</script>
</head>
<body>
<p>some content</p>
<input id="test1" type="file" name="file-upload" id="file-upload" value="2"/>
<p>some other content</p>
<script>test(1);</script>
</body>
Your SomeJSFunctionThatReturnsAvalue(); would pass it to test() function.
to get the value of "2" from your second question for use in a math function, just do:
var value = document.getElementById("test1").getAttribute("value");
document.write(parseInt(value, 10) + 3);
which returns 5.

To append the return value of your function to the name of the input tag, you can assign it to the name attribute of the input.
var counter = SomeJSFunctionThatReturnsAvalue();
var fileUpload = document.getElementById('file-upload');
fileUpload.name = fileUpload.name + "_" + counter;
You can get the type of a variable by using "typeof"
typeof myValue; // "string"
You can change this to an integer by using the parseInt() function.
var intValue = parseInt(myValue, 10);

You can change the name using .setAttribute("name", theNameUwantToChangeTo);:
function changeName(number){
var ele = document.getElementById("file-upload");
ele.setAttribute("name", b.getAttribute("name")+ "_" + number);
}
changeName(number);
To get the value, just .value:
function getV(){
return document.getElementById("file-upload").value;
}
var number = getV();
In case it does not return int, use parseInt()
function getV(){
return parseInt(document.getElementById("file-upload").value);
}
var number = getV();

Maybe you would benefit from looking into Angular.js or Ember.js if you are trying to do things like this. They can do data binding so that you can make readable and dynamic code just like what you are trying to create in your question.
If not that^ then this:
I saw you mentioned in a comment that you are dynamically creating the list. That is where you should be assigning the correct name with the counter (assuming there's no desire for counter to change dynamically. If there is a dynamic change then tell us what events are doing the change) Could you show us the code that is doing that please?

Related

Call function .oninput

JSFIDDLE
HTML:
<input type="number" id="strScore" class="attribScore" min=8 max=15>
<input type="number" id="strMod" class="attribMod" readonly="readonly">
Javascript:
/****************************************************************
document.getElementById("strScore").oninput = function update(e) {
var result = document.getElementById("strMod");
var attribScore = $('#strScore').val();
result.value = (Math.floor((attribScore / 2) -5));
}
******************************************************************/
var strScore = $('#strScore').val();
var strMod = $('#strMod').val();
var update = function(score, mod) {
attribMod = (Math.floor(score / 2) - 5);
mod.value = attribMod;
};
update(strScore,strMod);
When the left input is updated with an ability score, the right input should reflect the ability modifier.
The commented section of javascript is perfectly functional, but I would really rather not have a separate function for every input that needs to be updated like this - one function is far easier to isolate and troubleshoot in the future. What I'd like to do is have one function to which I can pass the score and modifier input values as arguments (strScore and strMod in this case) and have it update the modifier field via the .oninput event. My attempt at this is below the commented section of javascript. I feel like I'm just not connecting the dots on how to call the function appropriately or correctly update the Modifier input passed to the function.
Phew. Got pulled away from the desk. Here is a solution for you. You just need to make sure that the strscore is set with an id number. This way you can relate to what strmod you want to change.
Ex. strScore1 = strMod1 and strScore2 = strMod2
This will setup a scenario where you don't have to touch anymore JavaScript to do this same function in the future. Allowing you to add as many score and mod couplets as you want in the HTML part.
We are binding the 'input' event on the class of .attributeScore which allows us to set the function. There is no need to pass in values because they are already included by default. As long as the score input has a class of .attributeScore, then it will fire that function.
We can use this.value to grab the score value, and then sub-string out the identity of the score aka 1 for strScore1 from the this.id attribute of the input field.
If we concatenate that sub-string with #strMod we can update the value of the corresponding strMod attribute with inline math.
Here is the jsfiddle: http://jsfiddle.net/hrofz8rg/
<!DOCTYPE html>
<html>
<head>
<title>Some JavaScript Example</title>
</head>
<body>
<input type="number" id="strScore1" class="attribScore" min=8 max=15>
<input type="number" id="strMod1" class="attribMod" readonly="readonly">
<br>
<br>
<input type="number" id="strScore2" class="attribScore" min=8 max=15>
<input type="number" id="strMod2" class="attribMod" readonly="readonly">
<!-- JavaScript -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(".attribScore").bind({
'input':function(){
var attrib_num = this.id.substring(8,this.length);
$('#strMod' + attrib_num).val((Math.floor(this.value / 2) - 5));
}
});
</script>
</body>
</html>
Hope that helps! Enjoy!
Modifying your function to accept to dom nodes rather than two values would allow you to reuse the function in separate events that use different dom nodes relatively easily.
/****************************************************************
document.getElementById("strScore").oninput = function update(e) {
var result = document.getElementById("strMod");
var attribScore = $('#strScore').val();
result.value = (Math.floor((attribScore / 2) -5));
}
******************************************************************/
var update = function($score, $mod) {
var attribMod = (Math.floor($score.val() / 2) - 5);
$mod.val(attribMod);
};
document.getElementById("strScore").oninput = function update(e) {
var $score = $('#strScore');
var $mod = $('#strMod');
update($score, $mod);
};
Even better though would be able to dynamically figure out which mod element you should target based on which score element the event was triggered on, then you wouldn't need a separate function to do the calculation/update while keeping the code dry.

Get the tag name of a form input value

How does one get the .tagName of a value passed in an HTML form input? This is to check whether the value that has been passed is an 'iFrame'. The input is to only accept iframes
For example:
//HTML
<input type="text" id="iFrame">
<button id="butt">Push</button>
//JavaScript
document.getElementById("butt").onclick = function(){
var iframe = document.getElementById("iFrame").value;
console.log(iframe.tagName);
}
I think you are looking for
var iframe = document.getElementsByTagName("iFrame")
I perhaps did not ask the question in the best way, initially.
I wanted to check if the value passed in the input field was an "iframe" (the input is to only accept iFrames). Since .value returns a string and not an HTML tag, getting the tag name through basic methods would not work. I needed another way.
For anybody else who needs a quick solution, this is how I managed to do it:
document.getElementById("submit").onclick = function(){
var iframe = document.getElementById("iFrame").value;
var check1 = iframe.match(/iframe/g);
var check2 = iframe.match(/frameborder/g);
var check3 = iframe.match(/http:/g);
var check = check1.length + check2.length + check3.length;
if (check === 4) {
alert("good!");
}
}

Pass a javascript variable value into input type hidden value

I would like to assign value of product of two integer numbers into a hidden field already in the html document.
I was thinking about getting the value of a javascript variable and then passing it on a input type hidden.
I'm having a hard time to explain but this is how it should work:
Script Example
<script type="text/javascript">
function product(a,b){
return a*b;
}
</script>
above computes the product and i want the product to be in hidden field.
<input type="hidden" value="[return value from product function]">
How is this possible?
You could give your hidden field an id:
<input type="hidden" id="myField" value="" />
and then when you want to assign its value:
document.getElementById('myField').value = product(2, 3);
Make sure that you are performing this assignment after the DOM has been fully loaded, for example in the window.load event.
if you already have that hidden input :
function product(a, b) {
return a * b;
}
function setInputValue(input_id, val) {
document.getElementById(input_id).setAttribute('value', val);
}
if not, you can create one, add it to the body and then set it's value :
function addInput(val) {
var input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('value', val);
document.body.appendChild(input);
}
And then you can use(depending on the case) :
addInput(product(2, 3)); // if you want to create the input
// or
setInputValue('input_id', product(2, 3));
You could do that like this:
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
document.getElementById('myvalue').value = product(a,b);
</script>
<input type="hidden" value="THE OUTPUT OF PRODUCT FUNCTION" id="myvalue">
Hidden Field :
<input type="hidden" name="year" id="year">
Script :
<script type="text/javascript">
var year = new Date();
document.getElementById("year").value=(year.getFullYear());
</script>
Check out this jQuery page for some interesting examples of how to play with the value attribute, and how to call it:
http://api.jquery.com/val/
Otherwise - if you want to use jQuery rather than javascript in passing variables to an input of any kind, use the following to set the value of the input on an event click(), submit() et al:
on some event; assign or set the value of the input:
$('#inputid').val($('#idB').text());
where:
<input id = "inputid" type = "hidden" />
<div id = "idB">This text will be passed to the input</div>
Using such an approach, make sure the html input does not already specify a value, or a disabled attribute, obviously.
Beware the differences betwen .html() and .text() when dealing with html forms.
add some id for an input
var multi = product(2,3);
document.getElementById('id').value=multi;
<script type="text/javascript">
function product(x,y)
{
return x*y;
}
document.getElementById('myvalue').value = product(x,y);
</script>
<input type="hidden" value="THE OUTPUT OF PRODUCT FUNCTION" id="myvalue">
//prompts for input in javascript
test=prompt("Enter a value?","some string");
//passes javascript to a hidden field.
document.getElementById('myField').value = test;
//prompts for input in javascript
test2=prompt("Enter a value?","some string2");
//passes javascript to a hidden field
document.getElementById('myField').value = test2;
//prints output
document.write("hello, "+test+test2;
now this is confusing but this should work...

How to return a variable from a javascript function into html body

I am still new to javascript, and I am trying to get a function to return a variable using html & javascript. Basically the function should just return whichever radio button that the user clicks on, although at the moment I don't see anything being returned at all.
The function is here:
<script type="text/javascript">
function GetSelectedItem() {
var chosen = ""
len = document.f1.r1.length
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
chosen = document.f1.r1[i].value
}
}
}
return chosen
</script>
And then in the html section I have these radio buttons, and my attempt to get the variable "chosen" output to the screen.
<form name = f1><Input type = radio Name = r1 Value = "ON" onClick=GetSelectedItem()>On
<Input type = radio Name = r1 Value = "OFF" onClick =GetSelectedItem()>Off</form>
<script type ="text/javascript">document.write(chosen)</script>
At the moment nothing seems to be getting returned from the function (although if I output the variable 'chosen' inside the function then it is working correctly.
Thanks in advance!
Here's a little simpler approach.
First, make a few corrections to your HTML, and create a container to display the output:
<form name = "f1"> <!-- the "this" in GetSelectedItem(this) is the input -->
<input type = "radio" Name = "r1" Value = "ON" onClick="GetSelectedItem(this)">On
<input type = "radio" Name = "r1" Value = "OFF" onClick ="GetSelectedItem(this)">Off
</form>
<div id="output"></div>
Then change your script to this:
<script type="text/javascript">
// Grab the output eleent
var output = document.getElementById('output');
// "el" is the parameter that references the "this" argument that was passed
function GetSelectedItem(el) {
output.innerHTML = el.value; // set its content to the value of the "el"
}
</script>
...and place it just inside the closing </body> tag.
Click here to test a working example. (jsFiddle)
document.write takes a string, and outputs it as part of the HTML. This is not a live value that updates when the variable pointing at the string is updated.
For that, you will need to perform DOM manipulation.
Change your JavaScript function to something like that:
<script type="text/javascript">
function GetSelectedItem() {
len = document.f1.r1.length;
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
document.getElementById('test').textContent = document.f1.r1[i].value;
}
}
}
</script>
And then in the body:
<div id="test"></div>
As I put in the post. Using JQuery would make your life easy for this kind of task (and many others for the matter). The really nice thing about JQuery is that it often makes your JavaScript syntax much easier then you can learn the nitty gritty details of javascript as you go.
First, add the following script tag into your html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
Now you have the JQuery API
Then you could rewrite the function like this.
function GetSelectedItem(btnRadio)
{
var jqElem = $(btnRadio);
$('#output').html(jqElem.attr('value')); //attr('<name of attributre'>) gets the value of the selected attribute
}
Your html would look like this
<form name = "f1">
<input type = "radio" name = "r1" value = "On" onclick="GetSelectedItem(this)">On
<input type = "radio" name = "r1" value = "Off" onclick ="GetSelectedItem(this)">Off
</form>
<div id="output">
</div>
More or less, the .html() can both get and set the html of the selected element. So we are just simply inserting the value into the div tag.

How do I get a handle to a dynamically-generated field name in javascript?

I have a series of fields created dynamically based on database records. They will be named cardObject1, cardObject2, and so on for as many rows as necessary. I'm now trying to access a specific cardObject field in a function where the number is passed in, but am getting an error message.
The field looks like this:
<input name="cardObject241" value="2,$25.00,1" type="hidden">
The js code I'm using looks like this:
function deleteFromCart(id){
if (confirm("Are you sure you want to delete this item from your cart?")){
var voucherNbr = document.getElementById("voucherNbr").value;
var cardObjectArray = document.getElementById("cardObject"+id).value.split();
var amtToDelete = cardObjectArray[1];
alert("need to delete " + amtToDelete);
}
}
And the error I'm getting is
document.getElementById("cardObject" + id) is null
on this line:
var cardObjectArray = document.getElementById("cardObject"+id).value.split();
How can I get a handle to the cardObject field that ends with the number passed in as the id param?
You need to add an id="" attribute with the same name as the name attribute.
<input id="cardObject241" name="cardObject241" value="2,$25.00,1" type="hidden">
Firstly, your input field needs an id as well as a name, so it would look like this:
<input name="cardObject241" id="cardObject241" value="2,$25.00,1" type="hidden">
Secondly, if you have an object that may or may not exist, it's always a good idea to check for existence before you start manipulating properties:
var tempObj=document.getElementById("cardObject"+id)
if(tempObj) {
var cardObjectArray = tempObj.value.split();
...do your stuff with cardObjectArray....
}
You can use document.getElementsByName() or (cross-browser back to the Stone Age)
document.forms[formIndexOrName].elements["cardObject" + id].value.split(",")

Categories

Resources