Im trying to make a contact form where people will check either "one way" ticket or "roundtrip".
The first "one way" is checked when user reach the contact form and one(1) date field is shown, but if "roundtrip" is checked i want a 2nd date field to be shown with a return date.
Any ideas?
Simply observe the onchange event for the radio button. When it reaches you can check weather single trip or round trip is selected and then show / hide the div with the return date fields.
<!DOCTYPE html>
<head>
<script>
function hdl_change(e) {
document.getElementById('date2').style.visibility =
e.checked && e.id == 'opt_2' ? 'visible' : 'hidden';
}
</script>
</head>
<body>
<form name="myForm">
<input id="opt_1" type="radio" name="trip" value="oneway" onchange="hdl_change(this)"> One way<br>
<input id="opt_2" type="radio" name="trip" value="round" onchange="hdl_change(this)"> Roundtrip<br>
</form>
<div id="date1"> date 1 stuff ...</div>
<div id="date2" style="visibility:hidden"> date 2 stuff ...</div>
</body>
</html>
You would need to use javascript and on-event handlers to accomplish that, as such dependent/binding functionality doesn't come with the regular html form elements (To avoid confusion: same goes for it's potential children).
This answer will give you a pretty good hint how to do it as it answers a question related to a similar problem/request: https://stackoverflow.com/a/5137316/1093284
Update:
As you don't seem very experienced, here's a most simplistic example:
<!-- include jquery.js library first (http://jquery.com/) -->
<script src="jquery.js"></script>
<!-- then work the magic -->
<script>
$(document).ready(function(){
$('#inputB').hide;
$('#checkboxA').click(
function(e){
$('#inputA').show;
$('#inputB').hide;
});
$('#checkboxB').click(
function(e){
$('#inputB').show;
$('#inputA').hide;
});
});
</script>
And if you're fit enough to go pro with jQuery, check the other answer here on this page at https://stackoverflow.com/a/11743381/1093284
Last but not least, I think the answer here at https://stackoverflow.com/a/11743482/1093284 provides the best solution, as it's small and does not require a full-blown 32kb javascript library. On the other hand, inline javascript is actually a no-go. Whatever... it's the users that count and they will prefer a quicker-loading page over nicely coded stuff behind the curtains.
Related
Alright, so I have searched through a lot of relevant questions and tried the solutions, however, I am still unable to get this to work when I load it from my local machine using Google Chrome but it works when I copy and paste the script that is loaded in the browser page into the console.
I have a script as such in the html.erb code:
<script type="text/javascript">
$(document).ready(function(){
$(document).on("click","#<%=parent_question.id%>_<%=trigger_option%>",function() {
if($("#<%=parent_question.id%>_<%=trigger_option%>").prop('checked', true)){
<% for i in child_options %>
document.getElementById("<%=child_question.id%>").style.display = "block";
document.getElementById("<%=child_question.id%>_<%=#option[i].id%>").style.display = "block";
<%end%>
}
});
});
</script>
Basically what this code does is dynamically creating scripts to display following questions and input fields depending on whether or not the someone selects Yes in the radio button from the previous question.
The following is a sample of a script when outputting into a browser:
$(document).ready(function(){
$(document).on("click","#17_43",function() {
if($("#17_43").prop('checked', true)){
document.getElementById("18").style.display = "block";
document.getElementById("18_45").style.display = "block";
}
});
});
And the following HTML inputs and thingies it controls:
<p> Hello there :) </p>
<fieldset id="17">
Yes
<input type="radio" value="Yes" name="17" id="17_43">
No
<input type="radio" value="No" name="17" id="17_44">
</fieldset>
<p id="18" style="display: none;"> Thanks for helping!!! </p>
<input type="text" id="18_45" placeholder="HELLO" style="display: none;">
Any kind of help is much appreciated!
First, have you checked if the tag is correctly populated where <%=...=> is placed?
Second, this isn't an answer to your problem, but I think you should use a different structure to do this.
Like on your html instead of rendering divs with "ids" of numbers, you would render divs with a class like "question" and add a data attribute such as "data-id", with data-id reflecting the question id to whatever fields, or "mark" the inputs with an id such as "checkbox_#{id}"
Then you can have a js file:
$('.question').on('click', function() {
var id = $(this).data('id');
if ($('#checkbox_'+id).prop('checked', true)){
document.getElementById('p_'+id).style.display = "block";
document.getElementById('input_text_'+id).style.display = "block";
}
});
If you're adding the questions and whatever dynamically, you might want to make a function that binds the click handler, like:
function bindQuestions() {
$('.question').on('click', function() {
........
});
}
Then whenever you load new elements into the dom you can run "bindQuestions();"
I think I fixed it, thanks to gaetanoM for pointing it out.
I had some conflicting IDs in the HTML code that I had not noticed causing some conflicts in executing the scripts, following that I noticed that due to that, part of my code which does the opposite when selecting the radio button that hides the input and question fields conflicted with the ID's and such.
Thanks so much for all your help!
I'm actually working with Jquery and at some point I use Jquery selectors to make my page work. The issue here is that the HTML I work with can get very long depending on the data I work with and it looks like this.
HTML
<div class="mailing"></div>
<input type="text" class="mail_subject"/>
<input type="text" class="mail_body"/> <!-- I can have 1 to n number of these -->
<!-- Preview tags -->
<p class='main_subject'></p>
<p class='main_body'></p>
<!--
And a few more things we don't use here
-->
</div>
<div id="table1">
<table id="ranking">
<tbody>
<!-- Data, can have 0 to ~3500 rows -->
</tbody>
</table>
</div>
As you can see, my page is more or less divided in two parts, the <div class="mailing">, which contains a few forms, and the <div id="table1"> that is about displaying lots of data.
In my mailing div I have a few inputs and an auto-updated preview that takes the data from the inputs. What I have here is a kind of "mail builder" with the preview giving me the result with html formatting.
The problem here is about performance, my JQuery is slowed by the table and I got lag when I type in a form and I don't want it to search the whole document as I already know my data will be in the mailing div.
JS
$('.mailing').on('change click keyup keydown', function () {
// Here I append the mail_subject input to the preview
var text = $(this).val();
$('.main_subject').text($('.subject_select').val());
// Here I append each mail_body input to the preview
$('.bodies_select').each(function () {
text = $(this).val();
/*
* Some computation for the text
*/
jQuery('<span/>', {text: text}).appendTo('.main_body');
});
});
I have a few more functions like theses and a few more computation, but I think we got the idea of what my code looks like.
My question is, is there a way, when I use JQuery selectors like $('.main_subject') or $('.bodies_select') to not search the whole DOM document but only in my mailing div for example? The problem is that I can store my elements in variable since it as multiple occasion to be updated.
You can use context with jQuery to improve performances :
$('.bodies_select', '.mailing')
http://api.jquery.com/jquery/#jQuery1
You can even optimize the selectors with some technics :
https://learn.jquery.com/performance/optimize-selectors/
Sure, you just need to place the parent elemenent before
$('.mailing .main_subject')
You should probably read a bit about selectors
https://api.jquery.com/category/selectors/
Let me preface by saying this is all in relation to a Wordpress page. My knowledge of JS is lacking at best and the concept of installing/loading/enqueueing a function on one area of the site and then calling that function in another area of the site is a something that makes sense to me in my head but is very new to me in practice and might need a little explaining.
I have two separate javascript files that I would like to load on a single page, but toggle visibility/display of either based on radio button input. The JS is provided by a 3rd party and is offsite. Their provided code is this:
<script src="https://toolkit.rescuegroups.org/j/3/FzemP6HU/toolkit.js"></script>
and
<script src="https://toolkit.rescuegroups.org/j/3/4ANRW3x8/toolkit.js"></script>
Each file presents a separate set of filtered results from their database. How can I incorporate both onto a page but only have one or the other showing based on a radio button form input? I would like the page to start off with nothing visible (hopefully giving time for both JS to load in the background while the user selects an option) and then show one or the other depending on what they selected.
You can see a single one of these in action at http://pricelesspetrescue.org/adoptable-dogs/. I'm trying to incorporate the use of an additional file on that same page based on input from the user and only showing one or the other rather than both.
I have tried to manage the following
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type='text/javascript'>
function displayForm(c) {
if (c.value == "2") {
jQuery('#claremontdogContainer').toggle('show');
jQuery('#chdogContainer').hide();
}
if (c.value == "1") {
jQuery('#chdogContainer').toggle('show');
jQuery('#claremontdogContainer').hide();
}
};
</script>
<label>Please select a location to view:</label>
<form>
<input value="1" type="radio" name="formselector" onClick="displayForm(this)"></input>Chino Hills
<input value="2" type="radio" name="formselector" onClick="displayForm(this)"></input>Claremont
</form>
<div style="display:none" id="chdogContainer">
<script src="https://toolkit.rescuegroups.org/j/3/FzemP6HU/toolkit.js"></script>
<script type="text/javascript">
</script>
</div>
<!-- If I uncomment this second block the whole thing breaks
<div style="display:none" id="claremontdogContainer">
<script src="https://toolkit.rescuegroups.org/j/3/4ANRW3x8/toolkit.js"></script>
<script type="text/javascript">
</script>
</div>
-->
This gets pretty close to what I need. The problem I have is the second script load seems to conflict with the functions they provide in the script. It will display the initial result but does not carry any of the functionality that it should have. http://pricelesspetrescue.org/test-page/ Nothing is clickable inside those results and should be.
Been searching through various similar posts and the wordpress codex and...and...I just haven't been able to come up with anything that seems close enough to what I'm looking for to make the answer click in my head.
Edit: It seems that if I only load one of the scripts in either what I have above or the suggested answer below, all functionality is present when loaded. It's the loading of the second toolkit script that is breaking the page. I'm guessing one would need to be loaded then unloaded before loading the second for it to work. Any ideas?
The toolkit.js file you linked adds some common scripts to the DOM (via document.write function, which is not a good solution - see here: http://www.jameswiseman.com/blog/2011/03/31/jslint-messages-document-write-can-be-a-form-of-eval/), then populates an array (toolkitObjects) with a series of variables that are custom per file and finally loads some other scripts.
It also seems that each file loads a div with a specific class containing all the pets, and each div is identifiable by a specific class ( "rgtk-SOMEID" ) and therefore can be shown/hidden via javascript.
Here is an example of what you can obtain using the div class:
http://jsbin.com/loneyijuye/edit?html,output
I have a pretty standard html form with a few input boxes. I have a small div under each textbox that displays directions when the textbox has focus (the rest of the time they are hidden). The divs can also change color and display error messages.
I would like to be able to have one javascript function to show directions on focus, one function to show errors on blur, one function to hide directions/errors etc.
The problem that I am running into is how to best associate the textboxes and their respective divs. I have used a naming convention in which I gave the textboxes an ID like field1 and then called their div field1Div. This worked OK but something tells me there is a better way to do this.
What is the "correct" way to associate the div and textbox?
You may define custom attributes for input boxes.
<html>
<head>
<script>
function showHint(obj){
document.getElementById(obj.getAttribute("hintbox")).style.visibility = "visible";
}
function hideHint(obj){
document.getElementById(obj.getAttribute("hintbox")).style.visibility = "hidden";
}
</script>
</head>
<body>
<input hintbox="div1" onfocus="showHint(this)" onblur="hideHint(this)" />
<div id="div1" style="visibility:hidden">hint 1</div>
<input hintbox="div2" onfocus="showHint(this)" onblur="hideHint(this)" />
<div id="div2" style="visibility:hidden">hint 2</div>
</body>
</html>
http://jsfiddle.net/YhefV/
Labels might be the better way to go but if you want to use Divs - you can use something like this:
<html>
<head>
<script>
function giveDirections(obj){
obj.nextElementSibling.style.display="block"
}
function hideDirections(obj){
obj.nextElementSibling.style.display="none"
}
</script>
</head>
<body>
<input id="test" name="test" onfocus="giveDirections(this)" onblur="hideDirections(this)" />
<div style="display:none">Hi I am some directions</div>
</body>
</html>
http://jsfiddle.net/zq533/8/
using this.nextElementSibling - but I am not sure every browser supports - I tried it on FF,IE and Chrome and it worked.
I am sure there is a better way.
This is probably very simple, but could somebody tell me how to get the cursor blinking on a text box on page load?
Set focus on the first text field:
$("input:text:visible:first").focus();
This also does the first text field, but you can change the [0] to another index:
$('input[#type="text"]')[0].focus();
Or, you can use the ID:
$("#someTextBox").focus();
You can use HTML5 autofocus for this. You don't need jQuery or other JavaScript.
<input type="text" name="some_field" autofocus>
Note this will not work on IE9 and lower.
Sure:
<head>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#myTextBox").focus();
});
</script>
</head>
<body>
<input type="text" id="myTextBox">
</body>
Why is everybody using jQuery for something simple as this.
<body OnLoad="document.myform.mytextfield.focus();">
Think about your user interface before you do this. I assume (though none of the answers has said so) that you'll be doing this when the document loads using jQuery's ready() function. If a user has already focussed on a different element before the document has loaded (which is perfectly possible) then it's extremely irritating for them to have the focus stolen away.
You could check for this by adding onfocus attributes in each of your <input> elements to record whether the user has already focussed on a form field and then not stealing the focus if they have:
var anyFieldReceivedFocus = false;
function fieldReceivedFocus() {
anyFieldReceivedFocus = true;
}
function focusFirstField() {
if (!anyFieldReceivedFocus) {
// Do jQuery focus stuff
}
}
<input type="text" onfocus="fieldReceivedFocus()" name="one">
<input type="text" onfocus="fieldReceivedFocus()" name="two">
HTML:
<input id="search" size="10" />
jQuery:
$("#search").focus();
Sorry for bumping an old question. I found this via google.
Its also worth noting that its possible to use more than one selector, thus you can target any form element, and not just one specific type.
eg.
$('#myform input,#myform textarea').first().focus();
This will focus the first input or textarea it finds, and of course you can add other selectors into the mix as well. Handy if you can't be certain of a specific element type being first, or if you want something a bit general/reusable.
This is what I prefer to use:
<script type="text/javascript">
$(document).ready(function () {
$("#fieldID").focus();
});
</script>
place after input
<script type="text/javascript">document.formname.inputname.focus();</script>
The line $('#myTextBox').focus() alone won't put the cursor in the text box, instead use:
$('#myTextBox:text:visible:first').focus();
$("#search").focus();
You can also use HTML5 element <autofocus>
The Simple and easiest way to achieve this
$('#button').on('click', function () {
$('.form-group input[type="text"]').attr('autofocus', 'true');
});