Input
<input type="text" value="" id="row1">
<input type="text" value="" id="row2">
Need to get last character from row and pass it to javascript variable. Here is row1 and row2, need to get variables 1 and 2
I try to use this, but does not work
$('[id^="row"]').each(function (index, row) {
var row = row.id.substring(3);
alert (row);//this is only to check if value exists (alert or not)
});
No alert at all. But need: on first iteration (.each) var row is 1, on second, - 2, etc.
Used this as example. The example works, but my code not
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
Your code works fine, provided that:
You are actually including jQuery at some point (you didn't mention it in your question, but you appear to be using it)
You run the code after the elements exist.
Here's your code with jQuery included and where we ensure that the code doesn't run until after the elements exist: Live Copy | Live Source
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input type="text" value="" id="row1">
<input type="text" value="" id="row2">
<script>
(function($) {
$('[id^="row"]').each(function (index, row) {
var row = row.id.substring(3);
alert (row);//this is only to check if value exists (alert or not)
});
})(jQuery);
</script>
</body>
</html>
Note how the script tag is after the elements it operates on, so they exist when that script runs.
This would not work:
<script>
(function($) {
$('[id^="row"]').each(function (index, row) {
var row = row.id.substring(3);
alert (row);//this is only to check if value exists (alert or not)
});
})(jQuery);
</script>
<input type="text" value="" id="row1">
<input type="text" value="" id="row2">
...because when the script runs, the elements don't exist yet.
If for some reason you're not in control of where the script element goes, you can use jQuery's ready function to wait to run your code until the DOM has been loaded. But there's no need to do that if you control where the script tags go, just put them at the end of the document, just before the closing </body> tag.
More:
YUI Best Practices for Speeding Up your Website
Google Closure Library engineers on when DOM elements are ready
Related
After trying multiple ways of what I want to do, which all failed, I'm asking here. This is probably pretty basic, but I just can't do it.
What I essentially want to do:
Create a variable
"Assign" a text box (value) to it
Automatically have the variable's content change to whatever is put into the text box
Potentially have the variable's value used somewhere else immediately
If the user had to press a button to update the element using the variable's value, that'd be OK, too, I just want to have this done.
Alright, I have to correct myself. Another try worked, with the result of 'undefined'.
<head>
<meta id="test3" charset="utf-8">
<link rel="stylesheet" href=".\css\Starter.css">
<title id="test1">TITEL</title>
<script>
function txtSet(txtInp) {
var txt = txtInp.value
document.getElementById('txtP').innerHTML = txt
}
</script>
</head>
<body>
<input type="text" id="txtInp" onkeyup="txtSet(txtInp.value)"></input>
<p id="txtP"></p>
</body>
Try this one:
<body>
<script>
var a = "";
function changeVariable(){
document.getElementById('demo2').value=document.getElementById('demo').value;
}
</script>
<input type="text" id="demo" onkeyup="changeVariable()"></input>
<input type="text" id="demo2"></input>
</body>
I think that you're searching for onkeyup if it's so: you can use as it follows:
In your html
<input type="text" name="name" id="id" onkeyup="yourFunction(this.value);">
and in your js file
var theVariable;
function yourFunction(theTextInTheTextBox){
theVariable = theTextInTheTextBox;
}
It could also be onkeypress or onkeydown events, just try the three to see which is the one that you're actually searching for. To see the difference between the three I advise you to take a look at this link
I have this following code, I am trying to set value of hidden field with java script.
<script type="text/javascript" language="javascript">
var currentTime = new Date();
var tday=currentTime.getDate();
var tmonth=currentTime.getMonth();
var tyear=currentTime.getFullYear();
$("input[name='tday'").val(tday);
$('#tmonth').val(tmonth);
$('#tyear').val(tyear);
document.getElementById('tday').value='213';
</script>
<div id="edit_bs" class="edit_bs_st">
<form id='edir_pers' class='edit_pers_css' name='edit_pers' action='edit_pers.php' method='post'>
<input id='tyear' name='tyear'/>
<input id='tmonth' type='hidden' name='tmonth' />
<input id='tday' type='hidden' name='tday' />
<button type="submit">Submit</button></from>
The problem is that the value are not being passed to the 'edit_pers.php' they are blank. I have even tried document.getlementid.value to set the value but nothing works. I dont know what is wrong with my code.
hidden doesn't have anything to do with it. It's your call to the element that is bad.
THIS IS YOURS: BROKEN
$("input[name='tday'").val(tday);
THIS IS FIXED
$('input[name=tday]').val(tday);
Here's the result.
$(document).ready(function () {
var currentTime = new Date();
var tday=currentTime.getDate();
$('input[name=tday]').val(tday);
}):
As a side note, you don't need the redundant identifiers in your code. I'd personally go with this since you are probably required to have the name attribute.
HTML
<input type='hidden' name='tday' />
Javascript
$('input[name=tday]').val(tday);
http://jsfiddle.net/Uh7yn/
A part of your problem is that your code runs before the elements exists in the DOM.
Since you are using jQuery, the best way to circumvent this issue would be to use the document.ready handler. However, you will have to make sure that jQuery is loaded on the page.
$(function () {
//since your inputs have ids, you do not have to use any attribute selectors
$('#tday').val(213);
});
Also, you have a typo in the closing form tag.
I have the following codes:
<%int number=0;%>
<c:forEach var="row" items="${tAdmin.rows}" varStatus="totalRow" step="1">
<td><%=++number%></td>
<td>
<div id="content" style="table-layout:fixed; width:405px; word-wrap:break-word;">
<script language="JavaScript" type="text/JavaScript">
function load(){
var content='${row.content}';
document.getElementById("content").innerHTML=content;
document.getElementById("content").innerHTML=Utf8.decode(document.getElementById("content").innerHTML);
}
window.onload=load;
</script>
</div>
</td>
</c:forEach>
The problem is that it only shows the result of the last content instead of printing it out line by line according to number.
What you are creating, if you view the page source in the browser, would look something like this (note the ${row.content} will have already been replaced on the server):
<td>0<td>
<td>
<div id="content" style="table-layout:fixed; width:405px; word-wrap:break-word;">
<script language="JavaScript" type="text/JavaScript">
function load(){
var content='The first row content';
document.getElementById("content").innerHTML=content;
document.getElementById("content").innerHTML=
Utf8.decode(document.getElementById("content").innerHTML);
}
window.onload=load;
</script>
</div>
</td>
<td>1<td>
<td>
<div id="content" style="table-layout:fixed; width:405px; word-wrap:break-word;">
<script language="JavaScript" type="text/JavaScript">
function load(){
var content='Some different content';
document.getElementById("content").innerHTML=content;
document.getElementById("content").innerHTML=
Utf8.decode(document.getElementById("content").innerHTML);
}
window.onload=load;
</script>
</div>
</td>
<td>2<td>
<td>
<div id="content" style="table-layout:fixed; width:405px; word-wrap:break-word;">
<script language="JavaScript" type="text/JavaScript">
function load(){
var content='Yet some more content';
document.getElementById("content").innerHTML=content;
document.getElementById("content").innerHTML=
Utf8.decode(document.getElementById("content").innerHTML);
}
window.onload=load;
</script>
</div>
</td>
You're going to have many copies of function load() and many times where window.onload is assigned window.onload=load;
When this arrives at the browser and is interpreted, only the last definition of function load() will be in effect; only the last time you assign window.onload=load; means anything (because you keep replacing the value of window.onload) -- each redefinition of load() will replace the previous one - so only your last var content='${row.content}'; is ever executed.
In addition, you will have many <div> tags with the same id of "content" and that's not allowed.
The content of each of those <td><div>...</div></td> blocks can be set by the JSP/JSTL itself on the server -- there is no need to set the innerHTML via javascript.
You can use the totalRow varStatus that you set up to provide the number for the first <td> -- you don't need to increment your own counter.
You can use Expression Language (EL) to access the content value of each row.
Inline style="blah blah blah" sucks. Use that only if absolutely necessary.
Instead, put all this style in CSS targeting .contentbits:
style="table-layout:fixed; width:405px; word-wrap:break-word;"
becomes
.contentbits {
table-layout:fixed;
width:405px;
word-wrap:break-word;
}
The page fragment becomes much simpler:
<c:forEach var="row" items="${tAdmin.rows}" varStatus="totalRow" step="1">
<td>${totalRow}</td>
<td>
<div class="contentbits">${row.content}</div>
</td>
</c:forEach>
It's not the right way to do it, but a simple solution would be use addEventListener instead onload:
<%int number=0;%>
<c:forEach var="row" items="${tAdmin.rows}" varStatus="totalRow" step="1">
<td><%=++number%></td>
<td>
<div id="content<%=number%>" style="table-layout:fixed; width:405px; word-wrap:break-word;">
<script language="JavaScript" type="text/JavaScript">
window.addEventListener("load", function () {
var element = document.getElementById("content<%=number%>");
element.innerHTML=Utf8.decode('${row.content}');
}, true);
</script>
</div>
</td>
</c:forEach>
In fact your code is using only the last "onload" because, when loading the page, it will execute the javascript load callback only when finish full loading it. So, each time you loop is executed, it updates the load callback reference for the last one, so when onload is triggered, the last only will be executed.
But your code has other errors too. The content id, repeats at the code lot of times, that will make your div getElementById useless, because you have lot of ids that are equal. Ids must be unique to work property.
To finish, it's not a good pattern to mix your HTML with scripts inside, is better to have you logic file (javascript file) outside, then it can make changes in your code when finish to load, reading the html that was generated. You also can create data attribute in your div then read it by the javascript to manage all itens with a specific data attributes.
To keep it simple, I will add an example:
<%int number=0;%>
<c:forEach var="row" items="${tAdmin.rows}" varStatus="totalRow" step="1">
<td><%=++number%></td>
<td>
<div id="content<%=number%>" style="table-layout:fixed; width:405px; word-wrap:break-word;" data-content="${row.content}">
</div>
</td>
</c:forEach>
Now the script file (I'm using jQuery for this example works on any browser):
$(function() {
$("[data-content]").each(function(item) {
$(item).html(Utf8.decode(item.attr('data-content')));
});
});
I'm new here (and to web development in general), and I have been trying to understand why my function is not being executed on the specified event.
I found this post, and it seems exactly like what I want, but even this did not work:
html <input type="text" /> onchange event not working
Any help would be appreciated. My exact code follows. I have some text input fields (actually search boxes), and ultimately I want to have it check a checkbox when the user enters data into the text fields, but it doesn't even seem to call the function.
I have tried a few variants while reading the post mentioned above. Here are some input field attributes I have tried:
<input type="date" name="dt" size="10" value="2012-07-21" onChange="SetCheckBox('d')" />
<input type="search" size="10" name="sl" value="" onChange="SetCheckBox('n')" />
<input type="search" size="10" name="sf" value="" onkeypress="SetCheckBox('n')" />
<input type="search" size="20" name="st" value="" onkeypress="SetCheckBox(this);" />
and here is my javascript:
<script language="javascript" type="text/javascript">
Function SetCheckBox(id) {
alert (id.value);
document.write('test');
}
</script>
I have tried not passing any arguments and just doing a document.write, but it doesn't seem to be calling the function. And yes, javascript is enabled and working elsewhere on the page just fine!
The script is in the body, just below the form.
The (lack of) behavior is the same in multiple browsers.
Thank you for any help you can provide.
Ray
For javascript the function keyword is lowercase.
Function SetCheckBox(id)
needs to be:
function SetCheckBox(id)
Also, you're not passing object to get an id, so...
function SetCheckBox(id) {
var ele = document.getElemenyById(id);
alert (ele.value);
document.write('test');
}
Several issues apart from the already mentioned uppercase F in Function
your function passes a variable called id but expects a field
you pass a string that is not an ID and not referring to a field
only the last version using (this) will work, but there is no value to alert
document.write will WIPE the page and all scripts on it when it is invoked after page load (e.g. not inline)
So code should be EITHER
function SetCheckBox(id) {
var val = document.getElementById(id).value
alert (val);
document.getElementById('someContainer').innerHTML=val;
}
OR
function SetCheckBox(fld) {
var val = fld.value
alert (val);
document.getElementById('someContainer').innerHTML=val;
}
Based on your description, my guess is you want to do this: DEMO
<input type="date" id="dt" name="dt" size="10" value="2012-07-21"
onkeypress="SetCheckBox(this)" />
<input type="checkbox" id="dtChk" />
using this script
function SetCheckBox(fld) {
var checkbox = document.getElementById(fld.id+"Chk");
// check if something is entered, uncheck if not
checkbox.checked=fld.value.length>0;
}
and maybe even with this addition
window.onload=function() {
document.getElementById("dt").onkeypress();
}
which will check the box if the field is not empty at (re)load time
in javascript function keyword is written in small letters and here you wrote F in caps.
onkeypress and onchange event should works
<body>
<script type="text/javascript">
function SetCheckBox() {
alert("1");
}
</script>
<input id = "test" value="" onkeypress="SetCheckBox();" />
<input id = "test1" value="" onchange="SetCheckBox()" />
</body>
I know that this is an embarassingly easy question, but I can't figure out the problem, and that's why I'm asking the question, so please don't reiterate this point.
Anyway, I'm just working on something here, and when I tested my page to see how things were going, I realized that my calculate() method isn't clearing text input like I want it to.
Here is the markup and the script:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
function calculate(){
var valuea = document.form1.variablea.value;
var valueb = document.form1.variableb.value;
var valuec = document.form1.variablec.value;
document.form1.variablea.value = "";
document.form1.variableb.value = "";
document.form1.variablec.value = "";
}
</script>
</head>
<body>
<form name="form1">
a:<input name="variablea" value="" type="text">
<br/>
b:<input name="variableb" value="" type="text">
<br/>
c:<input name="variablec" value="" type="text">
<br/>
<input name="calculate" value="Calculate!" type="button" onClick="calculate()">
</form>
</body>
</html>
Please tell me if you see anything.
You might want to try using another name. I tried to call the "calculate" function but it keeps on giving me an error saying "calculate" is not a function. But when I call the function "calculateQuad" and change the onClick event to call "calculateQuad" it works.
Not very sure, but if you don't want to move to jQuery here's what you could try:
function calculate() {
var inputa = document.getElementById('inputa');
inputa.value = '';
}
Just test this, having an id "inputa" on one of the input boxes. I only know how to get elements by id, name or tag in raw Js. Of course, you could then extend your code to what you want using one of these methods to get your form elements.
Inside the onclick method is there a reference to the item you clicked. It is named the same as the name you put on the item, "calculate". This results in that "calculate" does not refer to the function, but the input tag.
To resolve this by either typing
onclick = "window.calculate()"
or rename the name of either the input-tag or the function.
change the name of the input button to something else:
<input name="calcul" value="Calculate!" type="button" onClick="calculate()">
and it works. Since the calculate function is residing directly under the global object, I have a weird feeling your name attribute is somehow overwriting it.
Just throwing this out there. I will take a deeper look at why this is happening though.