I've been trying to understand jQuery delegation by writing a short script, but I encountered 2 problems.
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<input type="text" id="text" />
<div id="msg"></div>
<script>
function showMsg() {
if ($("#text").val() === "") {
$("#msg").html("Your input is empty");
} else {
$("#msg").html("You have entered something")
}
}
$("#text").on("blur", showMsg());
</script>
</body>
1). This event delegation doesn't work as expected, the message "Your input is empty" always shows itself indefinitely. How to fix this?
2). In the showMsg() function I have to explicitly use $("#text") for the script to work, if I use $(this) it won't work. What if I have a lot of input fields that need to use this function, is it possible to uniformly define the function so that those input fields can use it without having to change anything in the function?
All you need to do is change
$("#text").on("blur", showMsg());
to
$("#text").on("blur", showMsg);
This will also fix your $(this) problem. You can set that back now.
Related
I am battling to get my javascript function to fire when a button is clicked on my html page.
My html code snippet:
<!DOCTYPE html>
<html>
<head>
<title>VLA SYSTEM</title>
Logout
<script
type ="text/JavaScript" src="logout.js"></script>
</head>
<body>
<form>
<script
type ="text/JavaScript" src="regGen.js"></script>
<script
type="text/JavaScript" src="submit.js"></script>
<input type="button" name="btnAssign" value="Assign Owner To Registration Number..." onclick="submit()">
My javascript code snippet:
function submit() {
window.alert("Information Captured And Stored To Database!");
}
The idea is that, when the user clicks on the button, the alert should fire informing the user that information has been captured, however, I am unable to get this alert to appear.
Any advice would be greatly appreciated.
The problem is that, unintuitively, inline handlers essentially implicitly use with (this) for the element that triggered the event, and for the parent element, and so on:
<form>
<input type="button" name="btnAssign" value="Assign Owner To Registration Number..."
onclick="console.log(submit === document.querySelector('form').submit)"
>
</form>
And form.submit is a built-in function will submit the form.
Either use a different function name, like doAlert:
onclick="doAlert()"
and
function doAlert() {
window.alert("Information Captured And Stored To Database!");
}
Or attach the listener properly using Javascript instead (inline handlers are pretty bad practice, and can result in unintuitive behavior like you're seeing):
document.querySelector('input[name="btnAssign"]).addEventListener('click', submit);
I'm starting to experiment with building Chrome extensions (first exposure to HTML and Javascript as well) and got stuck on a basic task. I have the popup.html file, which is what the user sees. What I'd like to do is have some placeholder text that is initially displayed to the user. The popup will also have a button so that when the user clicks on the button the placeholder text is replaced with something else.
Here is what I tested:
popup.html:
<!doctype html>
<html>
<head>
<title>Test Extension</title>
<script src="popup.js"></script>
</head>
<body>
<form id="testForm">
<input id="testButton" type="submit" value="testButton" />
</form>
<h3 id="textHeader">This will change.</h3>
</body>
</html>
popup.js:
function changeText() {
document.getElementById('textHeader').innerHTML = 'Changed!';
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('testForm').addEventListener('submit', changeText);
});
When I debug the script, I see the initial addEventListener call which calls changeText and causes the text in the popup to change to 'Changed!'. However, I then see a second call of the addEventListener, which then reverts back to the original popup.html form. The net effect is that 'Changed!' only appears for a brief instant.
Is there a way to make changes to the HTML file in an event listener permanent to get the intended behavior? I realize that I really need to gain an understanding of the DOM model and how Javascript can interact with it in the browser. I'm looking for a book or some other resource to consult (the Mozilla Developer Network site looked like a good authoritative source, but seemed kind of sparse), but in the meantime was hoping to gain at least some additional understanding by working through this simple example. Thanks!
EDIT:
Thank you everyone for the prompt responses! Disabling the form submissions makes sense. I'm adding this edit to my question post because the original task I was trying to achieve did in fact need to make use of a form.
What I'm trying to do is take in input from the user through a form, query an external site (ex: Wikipedia) for the phrase that user typed in, and then display in the popup content that's taken from the query.
Here is a skeleton outline of what I attempted:
popup.html:
<!doctype html>
<html>
<head>
<title>Test Extension</title>
<script src="popup.js"></script>
</head>
<body>
<form id="WikipediaForm">
<input type="text" id="userQuery" size="50"/>
<input id="submitQuery" type="submit" value="Ask Wikipedia" />
</form>
<h3 id="WikipediaResponse">placeholder</h3>
</body>
</html>
popup.js:
function changeText() {
var req = new XMLHttpRequest();
askURL = 'http://en.wikipedia.org/wiki' + encodeURIComponent(document.getElementById('userQuery').value);
req.open("GET", askURL, false);
req.onload = function (e) {
if (req.readyState === 4) {
if (req.status === 200) {
document.getElementById('WikipediaResponse').innerHTML = req.responseText; // i'm just dumping everything for now
}
} else {
console.error(req.statusText);
}
}
};
req.send(null);
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('WikipediaForm').addEventListener('submit', changeText);
});
This again also faces the same issue that I saw with the previous example where the response flashes for an instant before reverting back to the placeholder text. However, I can't follow the earlier answers now because I need the form to be submitted. What is the usual way of changing content in an event listener for a form?
On another note, I'm using the synchronous XMLHttpRequest call, which I know isn't recommend. But when I used the asynchronous call it didn't seem to go through and I couldn't figure out how to fix that, so that's another problem I'm also working on.
Use:
function changeText() {
document.getElementById('textHeader').innerHTML = 'Changed!';
//Returning false will prevent that the form submission completes
return false;
}
But if your form is never going to send data anywhere, you don't need a form at all (unless you're going to use a reset button for your fields). So you can just add type="button" to your element.
<body>
<input id="testButton" type="button" value="testButton" />
<h3 id="textHeader">This will change.</h3>
</body>
You need to return false from the event handler to prevent the normal form submission after the handler runs:
function changeText() {
document.getElementById('textHeader').innerHTML = 'Changed!';
return false;
}
I have some input field, and I call this in my js file
$(document).ready(function () {$('#input_id').focus(); });
but it doesn't launch. Even, when I launch it in my chrome console, I get no focus. How can it be
This is working sample for a text input, just match with your page code and see what you are missing as compared to this.
I assume that you have referred jquery js already and any other jquery functions work well in your page.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function ()
{
$('#input_id').focus();
});
</script>
</head>
<body>
<input type="text" id="input_id"/>
</body>
</html>
In any case please make sure that there is no js error in your page as
$('#input_id').focus(); must work fine individually, so only thing looks wrong could be reference to jquery, else some js error before code reaches to .focus() call on input_id.
Also you can validate if on your page focus for the input working fine, for this keep $('#input_id').focus(); in a script tag just before your body page ends/closes,
to make sure input control, jquery reference are placed correctly and page has no js errors, if this way too focus doesn't work then something is wrong with any of these 3.
First, some of you may notice that I reposted this question after deleting it. This is because it was mistakenly marked as a duplicate by someone who didn't bother to check - the question he linked to was about an <input> element; that solution does not work for textareas.
Anyway, consider the following code:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function caek() {
$('textarea[name=txt1]').val("cake");
$('textarea[name=txt1]').focus();
}
</script>
</head>
<body>
<div id="bar"></div>
<form name="frm1" id="cake">
<textarea name="txt1"></textarea>
</form>
<input type="button" value="Activate"
onclick="caek()">
</body>
</html>
When you run that, you will notice that the cursor is pushed to the start of the textarea, before the text. How can I make it come after all the text, at the end of the textarea? A non-inline solution would be optimal, but anything will do.
And a standalone solution (no plugins etc) would be perfect.
This is working for me.
function caek() {
txtArea = $('textarea[name=txt1]');
txtArea.val("cake");
txtArea.focus();
tmpStr = txtArea.val();
txtArea.val('');
txtArea.val(tmpStr);
}
This works.
$ta.text($ta.text()).focus()
Demo: http://jsfiddle.net/elclanrs/WWsBa/
You can use the rangyinputs jQuery plugin to do this in a cross platform way.
There's a demo here:
http://rangyinputs.googlecode.com/svn/trunk/demos/textinputs_jquery.html
Set the start and end to the same number and it'll set the cursor to that point (though it doesn't focus the textarea, so you have to tab into it to see the effect). In your case, you'd want to set it to the length of the text.
I don't understand what I'm doing wrong here. I just want my function to be called when I click the checkbox. Replacing the function call with alert() works, am I referencing my function incorrectly?
<html>
<head></head>
<body>
<script type="text/javascript">
function select(a){
document.getElementById("myDiv").innerHTML=""+a;
}
</script>
<input type="checkbox" onclick="select(1)">
<div id="myDiv">hi</div>
</body>
</html>
Thanks
Change the function name [e.g. selectFun]. select seems to be reserved keyword
This puzzled me as it looked ok to me too, So ran through the usual tests, eventually tried changing the function name and that worked fine.