I am trying to call the resetyear function and it's getting called also, but the flow stops at alert("over"). It doesn't transfer its control to resetmaster.
String flag = "";
flag = (String) session.getAttribute("flag");
System.out.println("flag = " + flag);
if (flag == null) {
flag = "";
}
if (flag.equals("yes")) {
%>
<script>
alert(1);
// resetyear();
dontreset();
//document.getElementById("checkyear").value = "1";
//alert(document.getElementById("checkyear").value);
</script>
<%} else if(flag.equals("no"))
{%>
<script>
alert(2);
//document.getElementById("checkyear").value = "2";
//alert(document.getElementById("checkyear").value);
resetyear();
</script>
<%}else{}%>
function resetyear(){
if(confirm("DO YOU WANT TO RESET THE YEAR?"))
{
alert("hello");
//document.forms['indexform'].action = "resetmaster";
//alert(document.forms['indexform'].action);
//document.forms['indexform'].submit();
alert("over");
form.action = "resetmaster";
form.submit();
alert(1);
}
For me it works:
document.getElementById("checkyear").value = "1";
alert(document.getElementById("checkyear").value);
http://jsfiddle.net/zKNqg/
Maybe your JS is not executed and you need to add a function() {} around it all.
You need to run your script after the element exists. Move the <input type="hidden" name="checkyear" id="checkyear" value=""> to the beginning.
It seems to work fine in Google Chrome. Which browser are you using?
Here the proof http://jsfiddle.net/CN8XL/
Anyhow you can also access to the input value parameter through the document.FormName.checkyear.value. You have to wrap in the input in a <form> tag like with the proper name attribute, like shown below:
<form name="FormName">
<input type="hidden" name="checkyear" id="checkyear" value="">
</form>
Have you considered using the jQuery Library? Here are the docs for .val() function.
The first thing I will try - determine if your code with alerts is actually rendered. I see some server "if" code in what you posted, so may be condition to render javascript is not satisfied. So, on the page you working on, right-click -> view source. Try to find the js code there. Please tell us if you found the code on the page.
Your code for setting value for hidden input is correct. Here is the example. Maybe you have some conditions in your if statements that are not allowing your scripts to execute.
Related
here is the function from inside a script
function dosubmit()
{
if (getObj("Frm_Username").value == "")
{
getObj("errmsg").innerHTML = "Username cannot be empty.";
getObj("myLayer").style.visibility = "visible" ;
return;
}
else
{
getObj("LoginId").disabled = true;
getObj("Frm_Logintoken").value = "3";
document.fLogin.submit();
}
}
i want to get the value of getObj("Frm_Logintoken")
as i can't pull the value from #Frm_Logintoken
using document.getElementById("#Frm_Logintoken")
this gives me null
because Frm_Logintoken only gets it's value when i click submit .
<input type="hidden" name="Frm_Logintoken" id="Frm_Logintoken" value="">
full page code
i found this online /getObj\("Frm_Logintoken"\).value = "(.*)";/g
but when i run it ... it gives me the same line again !
it's full code
https://hastebin.com/gurosatuna.xml
First:
Your checking if a value is empty with JS. However this is NOT needed as HTML does this for you. Add a attribute required and the form will not submit as long this value is empty
Documentation: https://www.w3schools.com/tags/att_input_required.asp
Second:
You could use the event handler 'on submit'. The code is not complete enough to know if u did this but I suppose you just added a Click handler on the button.
Documentation: https://www.w3schools.com/jsref/event_onsubmit.asp
When combining these two, you always have a username filled in and the code only executes when submitted. I hope this helps, if not please leave a comment and I will edit this answer.
EDIT: the answer on this SO will also help (not the checked on but the one below)
How can I listen to the form submit event in javascript?
I have a simple function to show / hide a div element. I have a javascript function to do that. I debugged this with Opera. The function sets the hidden value properly on the div element. I can see the div element disappear. However, when the function returns the div element reappears. The javascript function is in its own file:main.js:
function showhide(name){
var elem = document.getElementById(name) ;
if( elem.hidden == false ) {
document.getElementById(name).hidden = true ;
} else {
document.getElementById(name).hidden = false ;
}
}
The Html is:
<div class=wrap><p>
<div class=sidebar>
<FORM><input type="submit" value="Toggle" onclick="showhide('specname');"/></FORM></div>
<div class=main>main Div
<div id="specname">collapsible text</div></div></p></div>.
I have set debugging breakpoints in the javascript function showhide to see that the value is being set properly. But on function return, the value is reset.
It is probably something simple I am missing but can't seem to see it? Any ideas? Thanks!
The answers solved my problem. I was missing the fact that the submit repainted the page and I lost my changes. I changed the type=submit to type=button. And I removed the form to just an input element with type button. That worked very nicely. Thanks everyone for your help!!! I really appreciate your answers!
The following wont do anything in some browsers:
document.getElementById(name).hidden = true
change it to
document.getElementById(name).style.display = 'block' // and 'none' for the matching line
does that make it do what you need?
As others have pointed at, it is also submitting the page - either use a different element or change the function to start :
function showHide(e, name) {
e.preventDefault();
//do the toggle here
return false;
}
The problem is you are using a submit control which will submit to the server and refresh the page. You want to stop the submit or change the control type. Both of the following should work. I recommend the 2nd one.
Try this
<FORM><input type="submit" value="Toggle" onclick="showhide('specname'); return false;"/>
or this
<input type="button" value="Toggle" onclick="showhide('specname');"/>
Probably because when you click the button the form submits and it refreshes the page ?
You should not be using a form just to have a button that does something. Instead, try using
<button onClick="showhide('specname');">Toggle</button> (and get rid of the form entirely)
Try this for your showhide().
function showhide(name){
var elem = document.getElementById(name);
(elem.style.visibility == 'hidden'?elem.style.visibility = 'visible':elem.style.visibility = 'hidden');
}
OR similarly:
function showhide(name){
var elem = document.getElementById(name);
(elem.style.display== 'none'?elem.style.display= 'inline':elem.style.display= 'none');
}
Maybe try them both and see which you need.
Cheers.
I am using asp.net, JavaScript and HTML Handler.
In a asp button onclick event I am calling the JavaScript like this.
<asp:Button ID="btn_Tagging" CssClass="button" UseSubmitBehavior="false"
Text="Done" OnClientClick="DoneClick()" />
In the same page within the script tag I have written the JavaScript like this:
<script type="text/javascript">
function DoneClick()
{
var checkLocation = "";
var txtMM = document.getElementById("hdn_Tagging").value;///Id s of textbox assigned in code behind MB--
txtMM = txtMM.slice(0, -1);
var arrTxtMM = txtMM.split(",");
for(var j=0;j<arrTxtMM.length;j++)
{
var Loc = document.getElementById(arrTxtMM[j]).value;
if(Loc == "")
{
checkLocation = "";
break;
}
else
{
checkLocation += Loc + ":";
}
}
if(checkLocation != "")
{
var url ='Handler/newExifDetails.ashx?Id='+txtMM+'&Location='+checkLocation+'';
var completetbl, html;
$.getJSON(url,function(json)
{
$.each(json,function(i,weed)
{
var res = weed.res;
alert(res);
if(res == null)
{
}
else
{
window.top.location.href = "Dashboard.aspx";
}
});
});
}
else
{
alert("Please pick the locations for all objects");
}
}
</script>
Then when I click on button the alert within the JavaScript shows only if I put a breakpoint in Firebug or in Chrome Developers tool Script if I put breakpoint it works. Without putting that breakpoint neither the alert shows nor redirects.
It's a classical heisenbug. It would help if you could show us how the button looks like in the generated HTML code. Did you try using a simple alert as a click handler? Did you try adding the handler dynamically in JavaScript?
Try adding:
$('#btn_Tagging').click(DoneClick);
or:
$(function() { $('#btn_Tagging').click(DoneClick); });
at the end of your JavaScript code and remove the:
OnClientClick="DoneClick()"
from ASP.
I assume that the generated HTML button gets the id of "btn_Tagging" - am I correct? If it doesn't work then don't show us your ASP code but show us the generated HTML that gets to the browser instead, most importantly: what is its value attribute.
(Also, since you are already using jQuery for AJAX, I would suggest using jQuery also for the DOM manipulation. The way you do it it's easier to make mistakes and you're not using a library that is already loaded. See this reply for an example that even getElementById is easy to introduce bugs if you're not careful.)
Just try to use plain input type="button" control instead of asp:Button. Or rewrite your button as below:
<asp:Button ID="btn_Tagging" CssClass="button" UseSubmitBehavior="false"
Text="Done" OnClientClick="DoneClick(); return false;" />
The problem is in asynchronous mature of $.getJSON function so just after it called, execution context leaves the DoneClick function and called __doPostBack function added to btn_Tagging html control's onclick attribute by asp.net infrastructure.
i'm trying to write unobtrusive default/placeholder text in input (actually, relatively placed label over input, which hides on onFocus, and stays hidden if input isn't empty on onBlur), but I don't want to use jQuery, because this is the only javascript used on page - therefore using jQuery seems a bit over the top.
Please, how can I do this without jQuery?
Thank you.
EDIT: I know the idea (getElementByID), but I'm more looking into how to add it to document - preferably something you have used before. Thank you.
EDIT: Thank you all, I finally went with jQuery, seeing answers :] (my example is here: http://jsbin.com/ehega/3 - it's concept, I'll probably add more eye candy. As an answer I Robert Koritnik - because of valid points... and styling ;])
you will need to manually attach the onfocus and onblur events, having got a handle on the input with getElementById.
here is an example: http://www.aspsnippets.com/Articles/Watermark-TextBox-using-JavaScript.aspx
I suggest you use jQuery
jQuery is nothing more than a cross-browser library that makes it easier for developers to achieve something and not worry about browser particularities. And when you load it once (it's rather small) it's cached so I wouldn't worry because it will save you lots of development/testing time later.
No? Then do it manually but make it more reusable
But if you do decide to do something manually you can always use regular Javascript and manipulate DOM as you wish. You best friends in this case would of course be (as Andrew pointed out):
getElementById() and
getElementsByTagName()
functions, but since you'll be manipulating DOM and styles, make sure you test your code against all common browsers. If you use custom attributes on INPUT elements it's good to use the second function, so you'll attach additional functionality to all inputs at once and only to those that define that particular custom attribute like:
<input type=text id="inputX" name="inputX" placeholder="Enter something">
Your script would then get all inputs and you'd check for the custom attribute existance and attach events to those elements that do define that attribute. This way you won't depend on IDs and make your code universal so you can reuse it app wide. Or even on other projects.
Just a sidenote: Andrew's example works somehow differently than what you said would like to do (using labels), but I suggest you use the same approach, because you'll be running scripts anyway. For the sake of unobtrusiveness make sure that you set default content using Javascript so default values and styles on textboxes won't be set for those users that are not running Javascript.
You can use jQuery and still be unobtrusive and use the ability of HTML5 Browsers, make your input like this:
<input type="whatever" placeholder="Your Default Text"/>
I user Modernizr to check the html5 capabilities of the browser and if the browser doesn't understand the placeholder attribute than I use this little javascript to emulate this function.
if (!Modernizr.input.placeholder) {
$('input').each(function(){
var obj = $(this);
var placeholder = obj.attr('placeholder');
if (placeholder) {
obj.val(placeholder);
obj.focus(function(){
var obj2 = $(this);
if (obj2.val() == obj2.attr('placeholder')) obj2.val('');
});
obj.blur(function(){
var obj2 = $(this);
if (obj2.val() == '') obj2.val(obj2.attr('placeholder'));
});
}
});
}
It is unobtrusive, because you don't need any javascript in your html code. the function above can easily changed if you want to use any other framework. I wouldn't use a solution without any Framework, because the frameworks do a great job in working around the incompatibilities between browsers.
This is how I would do it, without JQuery. It grays out the control when it shows the default text, and allows entering the default text if need be. The "title" tag will fallback to a tooltip for people who disable JavaScript:
<html>
<body>
<input type="text" value="" title="default text" />
<script type="text/javascript">
function DefaultInput(e) {
// Get the elements
this.e = e
this.d = e.title
this.s = e.style
e.removeAttribute('title') // remove the tooltip
e.value = '' // IE cached value remove HACK!
// Bind the events
e.onblur = this.bind(this.onblur)
e.onfocus = this.bind(this.onfocus)
// Show the initial value in gray
this.onblur()
}
DefaultInput.prototype = {
bind: function(f) {
// Return `f` so it's always called as an object of DefaultInput
var o = this
return function(){
f.apply(o, arguments)
}
},
onblur: function() {
// Gray out my value and show the default text if my value's blank
if (!this.h && !this.e.value) {
this.s.color = 'gray'
this.e.value = this.d
this.h = true // true -> help text displayed
// false -> help text hidden/user entered value
}
},
onfocus: function() {
// Make the text black and blank the text if in "help" mode
if (this.h) {
this.s.color = 'black'
this.e.value = ''
this.h = false
}
}
}
// Make sure the page is loaded before
// running for twitchy browsers like IE
window.onload = function() {
// Add defaults for all text input elements which have a `title`
var L = document.getElementsByTagName('input')
for (var i=0; i<L.length; i++) {
var e = L[i]
if (e.type=='text' && 'title' in e)
new DefaultInput(e)
}
}
</script>
</body>
EDIT: Cleared up the comments a bit, fixed some IE bugs and made it so it looks for <input> tags with title's to make it so different pages have less conversion time rather than individually intitializing the input controls ;-)
I think that you need something like this:
<input type="text" onfocus="if (this.value == this.getAttribute('mydefaulttext')) this.value = '';" onblur="if (this.value == '') this.value = this.getAttribute('mydefaulttext');" mydefaulttext="click here..." value="click here..."/>
<input name="test" type="text" id="test" value="testValue" />
<script type="text/javascript">
var myInput = document.getElementById("test");
myInput.onfocus = function() {
this.value = '';
}
myInput.onblur = function() {
if(this.value == '') this.value = "testValue";
}
</script>
Here's how I do:
Online Working Example
http://jsbin.com/ehivo3 (source code)
HTML
<input type="text" name="myfield" id="myfield" value="Please, fill my field!!!" />
jQuery
$(document).ready(function() {
// Handle each input on focus() and blug()
$('input[type="text"]').each(function() {
$(this)
// Store the default value internally
// Don't use .val() because browser autofill will poison it
.data('defaultValue', $(this).attr('value'))
// Handle the focus() (when you enter the field)
.focus(function() {
if ($(this).val() == $(this).data('defaultValue'))
$(this).val('');
})
// Handle the blur() (when you leave the field)
.blur(function() {
if ($(this).val() == '')
$(this).val($(this).data('defaultValue'));
});
});
// Clear all fields with "default value" on submit
$('form').submit(function() {
$('input[type="text"]', $(this)).each(function() {
// If the input still with default value, clean it before the submit
if ($(this).val() == $(this).data('defaultValue'))
$(this).val('');
});
});
});
And that's all! No invalid or extra attributes, valid markup and all handled in your jQuery file. :)
In my HTML file, I have a JavaScript function named "CheckCaptcha". I am using following code line to execute that function when an image is clicked. It is not working. After hours of tweaking and modifying the code, it is not simply reaching to the location where the JavaScript function lies.
I am using this code line:
<input type="image" src="images/join.gif" name="SubmitStudent" onclick="CheckCaptcha();" width="98" height="31"/>
The JavaScript section is as below:
<script type="text/javascript">
function CheckCaptcha()
{
aler("-");
var CaptchaWord;
CaptchaWord = document.getElementById(StudentCaptchaImage);
alert(CaptchaWord);
if (CaptchaWord.length <= 4)
{
alert("Please enter words as seen in the image.");
return false;
}
}
</Script>
Actually, I am a new user, and StackOverflow is avoiding me to post the entire HTML section.
Try this:
function CheckCaptcha()
{
alert("-");
var CaptchaWord = document.getElementById('StudentCaptchaImage');
alert(CaptchaWord);
if (CaptchaWord.value.length <= 4)
{
alert("Please enter words as seen in the image.");
return false;
}
}
the .value attribute contains the value, the DOM element does not have a length property.
the gEBI method takes a string, not an identifier as you had it.. unless it was a variable.
your example had a typo in the first alert, I'm guessing you recently added it and it was not the initial problem.
If you're not sure of anything you should start alerting as many things as possible..
alert( typeof CaptchaWord.length )
Make sure getElementById takes a string:
CaptchaWord = document.getElementById("StudentCaptchaImage");
Have checked for any errors in JavaScript which may not be related to this particular function? Use Firebug to find any errors
I tried following code and its working
<script>
function CheckCaptcha(){
alert("test");
}
</script>
<input type="image" src="images/join.gif" name="SubmitStudent" onclick="CheckCaptcha();" width="98" height="31"/>
Have you tried returning false to cancel the event bubble?
onclick="CheckCaptcha(); return false"