Javascript inline HTML - javascript

I need to write HTML and Javascript code inline i.e. inside HTML Body (Need to display some random whole number value) I sought a lot of blogs but found no help so far in doing so. Please advise.
I wanna achieve this functionality:
<td class="vhead">Offered Calls</td>
<td>
<script>
Math.random();
</script>
</td>
</td>

Try this
<td id="demo"></td>
<script>
document.getElementById("demo").innerHTML = Math.random();
</script>

for the most simple case
<td class="vhead">Offered Calls</td>
<td>
<script>
document.write(Math.random());
</script>
</td>

Javascript does not work like this. It can with the help of templating libraries. Instead you will need to get a reference to the place in html you want to inject this random value. The below assumes you will have many and want a different random number in each.
<td class="vhead">Offered Calls</td>
<td class="random"></td>
<script>
window.document.onload = function(){
var elements = document.getElementsByClassName('random');
[].forEach.call(elements, function (el) { el.innerHTML( Math.random() ) });
}
</script>

Related

Using the current variable when tracking multiple variables with jQuery event

Below you'll find a simplified example of the code I am using and what I am trying to accomplish.
I'm tracking multiple variables with jQuery that need to call a function on a certain event. The problem is that I don't manage to use only that variable that just changed.
In the HTML body section I have a couple of input fields where people can fill in a number. That number should be formatted with commas as a thousand seperator. Thanks to Elias Zamaria I found an good solution for this (https://stackoverflow.com/a/2901298/7327579). Now I want this implemented with jQuery so I can track all of my variables that will get number inputs at once.
<html>
<title></title>
<head>
In the head of the html I insert my script to track my variables:
<script language="javascript">
var Currency = function() {
this.currencyType = $("#businessAuthorisation, #businessIncome, #entityIncome, #entityAuthorisation);
The function that formats the numbers and should only get the current number from the current variable that is being changed:
this.formatCurrency = function(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
};
};
Tracking starts and on the keyUp event my function is called. Only the current variable should be a parameter of the called function.
$(document).ready(function() {
var currency = new Currency();
currency.currencyType.keyup(function() {
currency.formatCurrency(this);
});
});
</script>
</head>
Here below are the concerning input fields in my form:
<body>
<form>
<table>
<tr>
<td><input type="number" name="entityAuthorisation" id="entityAuthorisation" value="<%=entityAuthorisation%>></td>
</tr>
<tr>
<td><input type="number" name="businessAuthorisation" id="businessAuthorisation" value="<%=businessAuthorisation%>"></td>
</tr>
<tr>
<td><input type="number" name="entityIncome" id="entityIncome" value="<%=entityIncome%>"></td>
</tr>
<tr>
<td><input type="number" name="businessIncome" id="businessIncome" value="<%=businessIncome%>"></td>
</tr>
</table>
</form>
</body>
</html>
How can I make sure that that the function only applies to the current element that caused the event?
In a jQuery event handler, this refers to the element that the event was triggered on. And you need to use .value to get the value of an input. So you should write:
$(document).ready(function() {
var currency = new Currency();
currency.currencyType.keyup(function() {
this.value = currency.formatCurrency(this.value);
});
});

Manipulating images via javascript, very simple

edit:
thanks a lot ya'll. Have a great night/day
All I'm trying to do is have javascript change the image src in a table cell by checking the id of the cell.
I have looked at every single related question on stack overflow and their solution. For some reason, my code won't work. Most likely syntax/lack of sleep issue
This js script in a table, located right above the src I'm trying to change depending on things:
<script>
function getImage(){
return "http://i.imgur.com/s5WKBjy.png"; //i literally just want to see if this works and it isn't
}
document.onload = function(){
document.getElementById('homeimage').src = getImage();
};
</script>
<td colspan="3"><img style="width:110px;height:128px;" id = "homeimage" onload="getImage()"></td>
<td colspan = "3"><img style="width:150px;height:128px;" id = "homeimage"></td>
neither of the above work. With the onload = "getImage()" and without. Am I being dumb? There's got to be something obvious I'm missing.
As if you don't want to use any ID the you can use this method,
This code works for n number td's in your table....
window.onload = function()
{
var rows = document.getElementsByTagName("table")[0].rows;
tds = rows[0].getElementsByTagName("td");
for (var n=0; n<tds.length;n++)
{
tds[n].getElementsByTagName('img')[0].src = getImage();
}
}
function getImage(){
return "http://i.imgur.com/s5WKBjy.png";
}
<table>
<tr>
<td colspan="3"><img style="width:110px;height:128px;"></td>
<td colspan = "3"><img style="width:150px;height:128px;"></td>
</tr>
</table>
You can't have two images with the same id. Name one homeimage1 and the other one homeimage2 for instance.
We can't use same id more than once in a single web page. Use different ids.
2nd change doucment.onload to window.onload
function getImage(){
return "http://i.imgur.com/s5WKBjy.png";
}
window.onload = function(){
document.getElementById('homeimageA').src = getImage();
document.getElementById('homeimageB').src = getImage();
}
<td colspan="3"><img style="width:110px;height:128px;" id = "homeimageA" onload="getImage()"></td>
<td colspan = "3"><img style="width:150px;height:128px;" id = "homeimageB"></td>
Things to note:
You have duplicate IDs, where IDs are should be unique.
You should use encodeURIComponent() to return the url value.
You don't have to use onload on the image itself.
You should bind the onload event on window object, that will do.
Before set the src just decodeURIComponent() to return value.
<td colspan="3"><img style="width:110px;height:128px;" id="homeimage1"></td>
<td colspan = "3"><img style="width:150px;height:128px;" id="homeimage2"></td>
Now changes in js:
<script>
function getImage(){
return encodeURIComponent("http://i.imgur.com/s5WKBjy.png"); //i literally just want to see if this works and it isn't
}
window.onload = function(){
document.getElementById('homeimage').src = decodeURIComponent(getImage());
};
</script>

Append data on button click

Hi StackOverflow people,
I have a question regarding a small web application that I am currently building.
I have a table of data, in this case phone numbers. I want to apply the phone number when the user clicks on a button next to the number in the table.
User clicks on a phone number in table.
Phone number gets added/appended to input field .
Any help is greatly appreciated!
Kind regards, Casper.
Try below code for the same :
$('#buttonId').click(function(){
$('#inputId').val($('#pnonumberId').val());
});
I think you are looking for something like this, let me know if anything else you are asking for.
Sample html assuming I understood the problem right:
<table>
<tr>
<td>1234567890</td><td><button class="btn">Select this</button></td>
</tr>
<tr>
<td>1111222233</td><td><button class="btn">Select this</button></td>
</tr>
<tr>
<td>2255667788</td><td><button class="btn">Select this</button></td>
</tr>
</table>
<input type="text" class="phone" />
Now for the javascript, something like the following should work:
var btns = document.querySelectorAll('.btn'),
phone = document.querySelector('.phone');
// looping through the nodelist and attaching eventlisteners
[].forEach.call(btns, function(btn) {
btn.addEventListener('click', function(event) {
// fetching the phone number
var selectedPhone = event.target.parentNode.previousSibling.textContent;
phone.value = selectedPhone; //setting the value
}, false);
});
Created a fiddle and tested. Link to fiddle: http://jsfiddle.net/subhamsaha1004/4f5cX/
Hope this helps.
If the number of rows in the table is more attaching event listeners to every button might not be good idea. The javascript should be changed to attach the listener to the table instead like this:
var table = document.querySelector('table'),
phone = document.querySelector('.phone');
table.addEventListener('click', function(event) {
// fetching the phone number
if(event.target.nodeName.toUpperCase() === 'BUTTON') {
var selectedPhone = event.target.parentNode.previousSibling.textContent;
phone.value = selectedPhone; //setting the value
}
}, false);
$('.phoneNumer').on('click', function(){
$('#input').attr('value', 'valueToshowInInput');
});
Something like this? You need jQuery for this.
fiddle here: http://jsfiddle.net/JbB4U/
<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<input type="text" value="" id="phone">
<table id="phone-list">
<tr>
<td><span class="phone-number">1XXXX-YYYYY</span><button class="click-number">Phone1</button></td>
</tr>
<tr>
<td><span class="phone-number">2XXXX-YYYYY</span><button class="click-number">Phone2</button></td>
</tr>
<tr>
<td><span class="phone-number">3XXXX-YYYYY</span><button class="click-number">Phone3</button></td>
</tr>
</table>
<script>
$(document).ready(function(){
var $phoneEdit = $("#phone");
$("#phone-list .click-number").click(function(){
$phoneEdit.val($(this).prev("span.phone-number").html());
});
});
</script>
Give an ID to the text field and also to the div section where the phone number is, Then use this jQuery code
$("#phone-list span.phone-number").click(function(){
$( "#phone" ).append($(this).val());
});

populate div by doing math on table cells

Trying to figure this stuff here out. Can't figure out if it's on the count of me having the numbers in the tds already. Is it takin em in as strings so it don't know how to do the math? I know I got this all wrong, but this is easy stuff I reckon so I hope you can set me straight. Much obliged.
<table id="Table">
<tr>
<td width="124" style="position: relative" rowspan="4">
<div id="percentage"></div>
</td>
<td>Total</td>
<td id="Total">259</td>
<td>Result</td>
<td id="Count">11</td>
</tr>
</table>
JS:
var total = $("Total");
var count = $("Count");
var Result = (Count/Total*100);
document.getElementById("percentage").innerHTML = Result;
That didn't work.
Also I need that there Result in .innerHTML to come out as a percentage. Should I just multiply it by 100 like I did here and attach a "%" manually?
Your JavaScript is looking for element types instead of the id's change your js to:
var total = parseInt($("#Total").text(), 10);
var count = parseInt($("#Count").text(), 10);
var Result = (count/total*100);
You are also not converting to a number.
you forget '#' to select by Id and you are not convert to int, so you can make it by jQuery in one line:
$('#percentage').text(parseInt($('#Count').text())/parseInt($('#Total').text())*100);

How to select value/innerHTML of a certain <td> within a certain <tr>? Using Javascript only. No jQuery

<table>
<tr>
<td>foo1</td>
<td>bar1</td>
<td><input type="button" id="button1" onClick="get(this);"></td>
</tr>
<tr>
<td>foo2</td>
<td>bar2</td>
<td><input type="button" id="button2" onClick="get(this);"></td>
</tr>
</table>
Goal: To get buttons button1 and button2 to trigger the same function get() which should get the value of the first <td> in the same <tr> the button resides in. Which is, in this case: foo1 and foo2 respectively.
This is a rough outline of the function which should help understand what I'm trying to achieve-
function get(element){
alert(element.tr.first_td.innerHTML);
}
I realize there was a jQuery solution to a similar problem. But I do not understand jQuery well enough to translate it back to JavaScript. If it is possible at all using JavaScript, please show me how.
Crawl up the parentNode twice to get to the tableRow element. From there, access the first td from the HTMLCollection of cells, and get the innerHTML value:
function find( element ) {
alert( element.parentNode.parentNode.cells[0].innerHTML );
}​
Fiddle: http://jsfiddle.net/jonathansampson/WuWnw/
Try this, since you have many tr and td tags right, so, you can do DOM Parsing. But you need to specify one ID for the table to get that table. For now lets call it foo-table.
var table = document.getElementById("foo-table");
var cells = table.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
alert(cells[i].innerHTML);
}
If you don't wanna give an ID and you are sure that there is only one table, then use this:
var table = document.getElementsByTagName("table");
var cells = table[0].getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
alert(cells[i].innerHTML);
}
Enjoy! Hope this helps! :) No jQuery or any other plugin. Pure JavaScript. :)
<table>
<tr>
<td id="button1_value">foo1</td>
<td>bar1</td>
<td><input type="button" id="button1" onClick="get('button1_value');"></td>
</tr>
<tr>
<td id="button2_value">foo2</td>
<td>bar2</td>
<td><input type="button" id="button2" onClick="get('button2_value');"></td>
</tr>
</table>
You shoul identify what you want to get using an ID so that you can easily retrieve it. This also helps prevent the chance of getting erroneous data. If you give the component an id you should be able to use document.getElementById() to get that component.
function get(element){
var obj = document.getElementById(element)
alert(obj.innerHTML);
}

Categories

Resources