Is there a way to reveald a secon input in a form after the first input has been filled? For example if I have a text input asking how many kids are going on the trip, person responds and a second input appears asking age range...
A simple example:
jsFiddle Demo
HTML:
<input id="in1" type="text" /><br>
<input id="in2" type="text" /><br>
javascript/jQuery:
$('#in1').change(function(){
if ( this.value != '' ) $('#in2').show().focus();
});
Update:
Note that you must wrap the jQuery code in a document.ready wrapper:
$(document).ready({
$('#in1').change(function(){
if ( this.value != '' ) $('#in2').show().focus();
});
}); //END document.ready
This prevents the javascript from attempting to bind an event (the change event) to a DOM element (the #in1 element) before that element exists in the DOM. $(document).ready() ensures the DOM has been fully rendered before attempting to create the event bindings.
Usually, all (or almost all) of your javascript/jQuery code is written within the $(document).ready() wrapper.
Notes:
The above code example uses jQuery, so you should reference the jQuery library in the <head> tags, comme ca:
<head>
<!-- other stuff in head -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
Note that if you use a CDN to load the jQuery library, as above, it is likely that jQuery is already pre-loaded from other websites visited previously.
If you want some fast lessons on jQuery, find free video tuts here:
https://www.thenewboston.com/videos.php?cat=32
or at
http://phpacademy.org
Yes, it is possible.
You should look at either JavaScripts onchange() or jQuery's .change() event to control this action. And then of course hiding and showing certain elements.
Related
Here we have a div with a onclick handler:
<div id="BorderContainer1282" onclick="alert('hello')">
<input id="Button925" type="button" value="Button">
</div >
When clicked it shows an alert dialog.
Does HTML support inline JavaScript in a child tag of the same name, like so:
<div id="BorderContainer1282">
<onclick>alert('hello');</onclick>
<input id="Button925" type="button" value="Button">
</div >
This question is not best practices. It is specifically about HTML supports setting events in a child tag of an HTML element as shown in the example.
NOTE: I tested the code above in example 2 and it does not work in my tests.
If it does not work, would using the following template be an acceptable alternative:
<div id="BorderContainer1282">
<script type="text/javascript">
document.getElementById('BorderContainer1282').addEventListener("click", function(event) {
(function(event) {
alert('hello');
}).call(document.getElementById("BorderContainer1282"), event);
});
</script>
<input id="Button925" type="button" value="Button">
</div >
Again, I'm not concerned about best practices now, only if this feature is supported.
I found a similar question here that is not a duplicate.
Your second example is not valid HTML; there is no <onclick> tag. The reason you are able to execute JavaScript in the first example is because of Event attributes for certain tags.
These attributes allow you to execute arbitrary JavaScript when a certain event is triggered on the given element, and although you are not concerned with best practices here, you should avoid using them if you want to keep your markup clean and organized.
What you are looking for is the <script> tag in your third example, which does allow for the insertion of JavaScript anywhere in your HTML markup, and is what you should use in this case. You can use this tag and addEventListener to attach an event handler to your div. This is the proper usage of the tag in this scenario:
<div id="BorderContainer1282">
<script type="text/javascript">
document.getElementById("BorderContainer1282").addEventListener("click", function(e) {
alert("Hello!");
});
</script>
<input id="Button925" type="button" value="Button">
</div >
Lastly, <script> tags are typically placed at the end of the <body> to ensure that all elements have been loaded before the script executes. You can also accomplish this by wrapping your JavaScript in a window.addEventListener("load", function(){ ... });.
I have a text with an input field. I want the field to start as blank, and when clicked upon, set the input's text to its correct value (saved in the "name" field, for instance).
If I do it this way, it works fine:
Buy <input type="text" name="eggs" onclick="this.value=this.name;"> tomorrow.
However, if I try to clean the DOM and move the function to a separate javascript file, it stops working:
HTML:
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
JS:
function showname(el) {
el.value = el.name;
}
function showname(el){
el.value = el.name;
}
.closeform{
width: 70px;
}
.closeform input {
width: 70px;
}
.closeform button {
width: 70px;
}
Buy
<span class="closeform">
<input type="text" name="eggs" onclick="showname(this);">
</span>
tomorrow.
I'm very new to Javascript - what am I missing here?
You say in your question:
However, if I try to clean the DOM and move the function to a separate javascript file, it stops working
Let's say you have 2 actual files in the same folder:
myscript.js contents:
function showname(el) { el.value = el.name; }
index.html contents:
<!DOCTYPE html>
<html><head><title>Demo</title>
<script src="myscript.js"></script>
</head><body>
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
</body></html>
OR
<!DOCTYPE html>
<html><head><title>Demo</title>
</head><body>
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
<script src="myscript.js"></script>
</body></html>
That should work perfectly...
However, in the comments you say:
I tried it with Fiddle - maybe the problem is in Fiddle interface.
That is where your problem was....
There is no separate javascript-file in jsfiddle.
The three code-blocks (html, js, css) get merged into one file.
Right-click the result-window in jsfiddle and look at the generated file.
Then notice the options (top right corner) from jsfiddle: by default the code is wrapped in an onload-method (suiting to the library you selected or window.onload if you are not using a library).
You can however place the script in the head or body, thereby not wrapping your code inside a function's scope (which then closes over the containing identifiers).
See http://jsfiddle.net/wf55a5qb/ for a working example.
The reason your example stack-snippet worked here on StackOverflow is that it's snippet-editor does not wrap the javascript codeblock in a (onload-like) function (when it combines the three code-blocks).
Having said and explained this, I do encourage you to set your events (Using obj.addEventListener/obj.attachEvent or the direct elm.onevent) from the/a script once the elements (that your script manipulates, place script as last element of the html-body) or page (using window.onload/etc) has loaded.
I posted this to clear up what actually went wrong so you don't make false models in your head about how javascript works (like "an external script runs in it's own scope" which no-one claimed but might be an assumption you might make) whilst still learning it!
Everything in JavaScript has a scope. Where you are defining your function, it is not visible to the input so the input doesn't know that function even exists. You can use window to make the function visible to it:
<input type="text" name="eggs" onclick="window.showname(this);"/>
window.showname = function (el)
Fiddle
I don't recommend global functions though. So then what else?
You can use the onclick function in JavaScript. To find elements in JavaScript, you use selectors. I'm using getElementById() this will get an element by it's id. A list of selectors are here
<input id="my_input" type="text" name="eggs"/>
Then in JavaScript:
document.getElementById('my_input').onclick = function () {
//Use this to refer to the element
this.value = this.name;
};
Fiddle
When doing this. Make sure all your code is wrapped in a window.onload. This will make sure the code is run at the right time:
window.onload = function () {
//Your code
};
JSFiddle automatically puts your code in this.
I've added a JQuery Masked Input plugin to my Web project but it's not working at all.
The plugin can be found here: http://digitalbush.com/projects/masked-input-plugin
I've included JQuery libray and the Masked Input plugin to my JSP, and called the mask function for my html <input> element:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- JS --->
<script src="js/jquery-1.11.0.js"></script>
<script src="js/masked-input-jquery-1.3.1.js"></script>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
$("#name").mask("99/99/9999");
</script>
<form id="" method="" action="">
<div>
<label for="name">
Name<b style="color: red">*</b>
</label>
<input name="studentName" maxlength="255" autofocus="autofocus" type="text" id="name"/>
......
When I access my JSP, even before typing anything on the text field, the following appears on Chrome console:
Uncaught ReferenceError: iMask is not defined
Can you help me? Is there anything wrong with the code?
This may or may not fix your current problem, but your call to .mask will not work because it runs before the rest of the page (where your input fields are) is parsed.
You need to wrap the call in the jQuery document ready function:
$('document').ready(function() {
$("#name").mask("99/99/9999");
});
This tells the script to wait until the page is loaded enough for the browser to know about the input fields in the document.
As an additional comment best practices say to put all script tags (with some exceptions) just before the closing body tag.
Otherwise you should move the script tag into the head with the rest of the tags.
That's because jQuery is downloaded but not ready yet. Try
$(function(){
// your code goes here
});
You need to wrap your jQuery in document.ready as several folks have already mentioned. You also need to adjust your mask to match your desired input. I assume you only want alpha characters allowed. This JSFiddle shows you an example with that assumption.
If you want alphanumeric just replace 'a' with '*'. Below is the jQuery Code:
$(function() {
//The # of "a"s you enter depends on your max field input
//The "?" makes any character after the first one optional
$("#fname").mask("a?aaaaaaaaaaaaaaaaaaaaaaaa");
$("#lname").mask("a?aaaaaaaaaaaaaaaaaaaaaaaa");
});
It should also be said that using the masked input plugin may not be the best option to validate a name as it is meant for fixed width inputs. If you want to validate alpha characters of varying lenghts consider doing something like this instead.
I have a web application which replaces content. This content has jquery ui check buttons. When I replace the content if a button already exists then don't add it again:
if(!$('label[for=checkWeekM]').hasClass('ui-button'))
$('.checkWeek').button();
If I push the button (its state is checked) and if I replace the content, the button starts locked until the same content is replaced again.
I use Backbone.js to replace the content
jsfiddle
How can I unlock the check button?
You are duplicating id attributes and that leads to bad HTML, bad HTML leads to frustration, frustration leads to anger, etc.
You have this in your template that you have hidden inside a <div>:
<input type="checkbox" class="checkWeek" id="checkWeekM" />
<label for="checkWeekM">L</label>
Then you insert that same HTML into your .content-central. Now you have two elements in your page with the same id attribute and two <label> elements pointing to them. When you add the jQuery-UI button wrapper, you end up with a slightly modified version of your <label> as the visible element for your checkbox; but, that <label> will be associated with two DOM elements through the for attribute and everything falls apart.
The solution is to stop using a <div> to store your templates. If you use a <script> instead, the browser won't parse the content as HTML and you won't have duplicate id attributes. Something like this:
<script id="template-central-home" type="text/x-template">
<div data-template-name="">
<input type="checkbox" class="checkWeek" id="checkWeekM" />
<label for="checkWeekM">L</label>
</div>
</script>
and then this to access the HTML:
content.view = new ContentView({
model: content,
template: $('#template-' + template_name).html()
});
Demo: http://jsfiddle.net/ambiguous/qffsm/
There are two quick lessons here:
Having valid HTML is quite important.
Don't store templates in hidden <div>s, store them in <script>s with a type attribute other than text/html so that browser won't try to interpret them as HTML.
I took a detailed look at your fiddle after you mentioned this problem. The solution I suggested here was more like a quick fix.
If you want to follow the right thing to avoid long term problems and side effects you should consider what is mentioned here. This way your problem is solved and there are no other bugs.
I have a form validation routine in JS which cycles through elements of a the first form on the page. I read the size of the elements array like this:
maxi=document.forms[0].elements.length;
This works fine in IE returning 23. In FF it always returns 0 and no validation at all is performed.
Any suggestions?
Thanks!
Move your javascript after the mark up or make sure that it runs after the document is loaded. Sounds like in FF the code is running before the form has been added to the DOM.
You might also consider using a javascript library, such as jQuery (I would recommend this), MooTools, Prototype, etc. to iron out a lot of the inevitable cross-browser issues you will have. Using jQuery, and the validation plugin, the validation code is very simple, using CSS classes to help with validation.
<script type="text/javascript" src="jquery.js" />
<script type="text/javascript">
$(function() { // run on document load
$('form').validate(); // use validation plugin to validate form
});
</script>
<form ...>
<input type="text" id="txt" name="txt" class="required" /> <!-- a required element -->
<input type="text" id="num" name="num" class="required number" /> <!-- a required, numeric element -->
...
</form>
You should try some interactive javascript console to test issues like this -
but, for this particular thing, you could use the "for ...in" form of for to iterate over the elements:
http://en.wikipedia.org/wiki/Foreach#JavaScript
Probably, however, it is the "elements" property which is non-standard there, so you will need to check the DOMs to get to a better way to retrieve the form widgets as objects.
And finally: beware of cleint side verification: it is often a burden to users and, if special care is not taken, it is to ease to have your forms stop working on a variety of browsers/platforms due to a verification which is mostly meaningless anyway (since you must verify the lenght of data entered server side in either case)