Modify placeholder attribute when radio input is selected - javascript

I am trying to update the HTML5 placeholder attribute when the a radio button is selected. I'm not using JQuery, so would prefer an inline JavaScript solution. I know I'm missing something simple, but am trying to teach myself!
<script type="text/javascript">
function ModifyPlaceHolder1 () {
var input = document.getElementById ("MyQuery");
input.placeholder = "Search books e.g. Harry Potter";
}
function ModifyPlaceHolder2 () {
var input = document.getElementById ("MyQuery");
input.placeholder = "Search journals e.g. New Scientist";
}
</script>
<input type="text" id="MyQuery" placeholder="Search resources" name="q" />
<input type="radio" value="" id="All" name="s.cmd" checked="checked" />
<label for="All">All</label>
<input type="radio" onclick="ModifyPlaceHolder1 ()" value="" id="Books" name="s.cmd" checked="checked" />
<label for="Books">Books</label>
<input type="radio" onclick="ModifyPlaceHolder2 ()" value="" id="Journals" name="s.cmd" checked="checked" />
<label for="Journals">Journals</label>

Here's a way to do this without any inline JS. A wee bit cleaner, and easier to track (IMO).
<input type="text" id="MyQuery" placeholder="Search resources" name="q" />
<input type="radio" value="" id="All" name="s.cmd" checked="checked" />
<label for="All">All</label>
<input type="radio" value="" id="Books" name="s.cmd" checked="checked" />
<label for="Books">Books</label>
<input type="radio" value="" id="Journals" name="s.cmd" checked="checked" />
<label for="Journals">Journals</label>
var books = document.getElementById("Books");
var journals = document.getElementById("Journals");
var input = document.getElementById("MyQuery");
books.onclick = function() {
input.placeholder = "Search books e.g. Harry Potter";
}
journals.onclick = function() {
input.placeholder = "Search journals e.g. New Scientist";
}

I would program it with a single function as below:
<script>
function ModifyPlaceHolder(element) {
var data = {
All: 'Search resources',
Books: 'Search books e.g. Harry Potter',
Journals: 'Search journals e.g. New Scientist'
};
var input = element.form.MyQuery;
input.placeholder = data[element.id];
}
</script>
<form>
<input type="text" id="MyQuery" placeholder="Search resources" name="q">
<label for="All"><input type="radio" onclick="ModifyPlaceHolder(this)" id="All" name="s.cmd" checked> All</label>
<label for="Books"><input type="radio" onclick="ModifyPlaceHolder(this)" id="Books" name="s.cmd"> Books</label>
<label for="Journals"><input type="radio" onclick="ModifyPlaceHolder(this)" id="Journals" name="s.cmd"> Journals</label>
</form>
Note that:
Not all browsers in use support the placeholder attribtue
Label elements should really wrap the control they apply to, otherwise some browsers won't correctly associate them. Wrapping also means the label acts as part of the button, so clicking on the lable checks the button too.
Only one radio button can be checked at a time, so only set one as the default checked.
Putting the controls in a form makes them easier to access.
When you see a string of identical listeners that are all contained in one element, you can look to putting a single listener on a parent element. Search for "event delegation".

Try this:
<script>
function ModifyPlaceHolder(element) {
var data = {
All: 'Search resources',
Books: 'Search books e.g. Harry Potter',
Journals: 'Search journals e.g. New Scientist'
};
var input = document.getElementById("MyQuery");
input.placeholder = data[element.id];
}
</script>

Related

Is there a way to assign the user's input and/or selection into the message?

<input type="radio" name="T" id="twenT">20
<input type="radio" name="T" id="sixT">60
<input id="uIn"></input>
<button onclick="function()">
How do I make it so that the user selects one option or inputs text and then the text message changes to the text that was selected/entered.
Pure JavaScript is preferred.
Try this
I changed to name="T" to make them valid radios
I also closed the A to make it valid. If you want to click the link and change, then we can remove the button
const href = "sms://+15552345678;?&body="
const sms = document.getElementById("sms");
const uIn = document.getElementById("uIn");
document.getElementById("changeMsg").addEventListener("click",function(e) {
const val = document.querySelector("input[name=T]:checked");
if (val) {
sms.href = href.split("body=")
.join(`body=${encodeURIComponent(val.value)}&uIn=${encodeURIComponent(uIn.value)}`)
console.log(sms.href)
}
else {
console.log("radio not checked")
}
})
<input type="radio" name="T" value="twenT">20
<input type="radio" name="T" value="sixT">60
<input id="uIn" type="text" value="" />
<a id="sms" href="sms://+15552345678;?&body=CHANGE%20THIS">Call us</a>
<button id="changeMsg" type="button">Change</button>

populate 'today + x days' as form input value [duplicate]

I am trying to use the innerHTML method on an input tag and all i get back is a blank string. Here is the code i am useing.
javascript
function setName(ID){
document.getElementById('searchtitle').innerHTML = "Enter " + ID.innerHTML;
}
HTML
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)">Last Name</input><br/>
<input type="radio" name="searchtype" value="phonenumber" onclick="setName(this)">Phone Number</input><br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label><br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;"></input>
What is supposed to happen is depending on which radio button I pick the label for the input box should change. I can make the label.innerHTML=radio.value but the values are named for my php code and not formated nicely(ie. phonenumber vs. Phone Number) this is why I am trying to use the innerHTML of the radio button.
Any help I could get would be greatly appriciated.
you should embed input inside of label tag. input tag should closed by />. It's semantic HTML. When you do this clicking on label activate the input. InnerHTML only works for label then. It will return you label value.
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;" />
</label>
JavaScript:
console.log(document.getElementById('searchtitle').innerHTML); // returns 'Enter Last Name'
If you want the value of an input tag, you want to use .value.
First, add labels around your inputs. Second, use getName(this.parentNode). Finally, call innerText instead of innerHtml.
<html>
<head>
<script>
function setName(el){
document.getElementById('searchtitle').innerHTML = "Enter " + el.innerText;
}
</script>
</head>
<body>
<label><input type="radio" name="searchtype" value="name" onclick="setName(this.parentNode)"/>Last
Name</label><br/>
<label><input type="radio" name="searchtype" value="phonenumber" onclick="setName(this.parentNode)"/>Phone
Number</label><br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label><br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;"></input>
</body>
</html>
Complete edit.
Ok, I figured out what you were looking for. First off, you've got to fix your HTML (don't put text inside of an input... and don't next an input inside of a label).
<label for="test">Last Name</label>
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)" />
<br/>
<label for="test2">Phone Number</label>
<input type="radio" id="test2" name="searchtype" value="phonenumber" onclick="setName(this)" />
<br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label>
<br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;" />
JavaScript (in Jquery, for brevity):
function setName(elem)
{
$('#searchtitle').html('Enter ' + $('label[for="'+elem.id+'"]').html());
}
You have closed the Input tag improperly with </input>
this should be
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)"/>Last Name<br/>
<input type="radio" name="searchtype" value="phonenumber" onclick="setName(this)"/>Phone Number<br/>

Passing radio buttons to be redirected to a new page

I am trying to reword this the best I can
I want it so that when someone goes to a page, they get the value of a radio button that is a link that sends them there once they click submit.
here's the code i've tried
<form name = "quoted" method="get">
<input id = "poster" type="text" name="poster" required="required" placeholder = "Credited Individual."> <br>
<textarea class = "actual_quote" name = "actual_quote" required="required" placeholder = "Write the question here!"></textarea><br><br><br>
<div class = "checkboxes" required="required">
<h3 style = "margin-top:-20px;">Please select one catagory that the quote falls into.</h3>
<label for="x"><input type="radio" name="x" value="stupid.php" id = "x" checked="checked" /> <span>stupid</span></label><br>
<label for="x"><input type="radio" name="x" value="stupider.php" id = "x" /> <span>stupider</span> </label><br>
<label for="x"><input type="radio" name="x" value="stupidest.php" id = "x"/> <span>stupidest</span></label>
</div>
<input id = "submit1" type="submit"><br>
</form>
and here's the code that is supposed to make it work, but it doesn't.
$(function(){
$('form').submit(function(event){
event.preventDefault();
window.location = $('input[type=radio]:checked').val();
});
});
what am I doing wrong?
I just want the user to be able to select one radio option, and once that radio option is selected and they press submit redirect them to that one certain page that the value is pointing to.
Please help! Any suggestions welcome!
-Connor
Try this
<script type="text/javascript">
function get_action(form) {
form.action = document.querySelector('input[name = "x"]:checked').value;
}
</script>
<form name = "quoted" method="get" onsubmit="get_action(this);">
<input id = "poster" type="text" name="poster" required="required" placeholder = "Credited Individual."> <br>
<textarea class = "actual_quote" name = "actual_quote" required="required" placeholder = "Write the question here!"></textarea><br><br><br>
<div class = "checkboxes" required="required">
<h3 style = "margin-top:-20px;">Please select one catagory that the quote falls into.</h3>
<label for="x"><input type="radio" name="x" value="stupid.php" id = "x" checked="checked" /> <span>stupid</span></label><br>
<label for="x"><input type="radio" name="x" value="stupider.php" id = "x" /> <span>stupider</span> </label><br>
<label for="x"><input type="radio" name="x" value="stupidest.php" id = "x"/> <span>stupidest</span></label>
</div>
<input id = "submit1" type="submit"><br>
</form>
This will work. Please vote if it worked. :)
Your code seems to be working fine on jsfiddle.
$(function(){
$('form').submit(function(event){
event.preventDefault();
window.location = $('input[type=radio]:checked').val();
});
});
Make sure that the php files are valid and working. If the page is being loaded but not displayed, it might be a problem with your php files. If no page is being loaded when you click submit, try using a different browser, as the code here works fine.

jQuery to Validate an Input Text Control based on Radio Selection

How do I validate that the input text corresponding to the radio option is checked?
For example, using the image above:
If Contact 1's E-Mail radio option is selected, Contact 1's E-Mail text field cannot be blank, but Contact 1's Phone and US Mail text fields are still permitted.
If Contact 2's US Mail radio option is selected, Contact 2's US Mail text field cannot be blank, but Contact 2's Phone and E-Mail text fields are still permitted.
I have built the form above using the HTML below, but you can play with my Fiddle here: fiddle.
BEGIN UPDATE: I have a newer fiddle with better code here:
fiddle2
It has more instructions in the HTML and a closer attempt at my jQuery. For some reason, though, it still does not seem to be doing anything.
END UPDATE
I have tried naming the fields so that my jQuery can parse them, but that does not mean there is not a better way.
<body>
<form name="jp2code" action="#" method="POST">
<fieldset>
<legend>Contact 1</legend>
<span>
<input type="radio" id="group1_PhoneRadio" name="group1"/>
<label for="group1_PhoneText">Phone:</label>
<input type="text" id="group1_PhoneText" name="group1_PhoneText"/>
<br/>
<input type="radio" id="group1_EMailRadio" name="group1"/>
<label for="group1_EMailText">E-Mail:</label>
<input type="text" id="group1_EMailText" name="group1_EMailText"/>
<br/>
<input type="radio" id="group1_USMailRadio" name="group1"/>
<label for="group1_USMailText">US Mail:</label>
<input type="text" id="group1_USMailText" name="group1_USMailText"/>
</span>
</fieldset>
<fieldset>
<legend>Contact 2</legend>
<span>
<input type="radio" id="group2_PhoneRadio" name="group2"/>
<label for="group2_PhoneText">Phone:</label>
<input type="text" id="group2_PhoneText" name="group2_PhoneText"/>
<br/>
<input type="radio" id="group2_EMailRadio" name="group2"/>
<label for="group2_EMailText">E-Mail:</label>
<input type="text" id="group2_EMailText" name="group2_EMaiText"/>
<br/>
<input type="radio" id="group2_USMailRadio" name="group2"/>
<label for="group2_USMailText">US Mail:</label>
<input type="text" id="group2_USMailText" name="group2_USMailText"/>
</span>
</fieldset>
<div>
<input type="submit" name="submit" value="submit" />
</div>
</form>
</body>
What is the best way to write the jQuery?
I am new to jQuery, but I attempted my hand at it based on some Show/hide examples.
What I created below does not work, but hopefully indicates what I am trying to accomplish.
$(function() {
$("input[type='radio']").change(function() { // when a radio button in the group changes
var id = $(this).id;
var index = id.indexOf('group');
if (index == 0) { // is there a better way to do this?
var groupN_Len = 7; // Length of 'groupN_'
var radio_Len = 5; // Length of 'radio'
var preStr = id.substring(0, groupN_Len);
$"input[name*='preStr']".validate = null; // clear validation for all text inputs in the group
var postStr = id.substring(groupN_Len + 1, id.Length() + 1 - radio_Len); // extract Phone, EMail, or USMail
$(preStr+postStr+'Text').validate({ rules: { name: { required: true } } });
}
});
});
To make sure that the radiobutton is checked for each field, add attribute required="" in one of the radiobuttons for each fieldset.
demo
OK, whatever radio button is selected in the Contact Group's Contact Preferences, that corresponding text field is required.
Here is where I am so far on my jQuery checking:
EDIT:
Modified with tilda's important detail about adding '.' to the class name.
Added Required Attribute: how to dynamically add REQUIRED attribute to textarea tag using jquery?
Removed Required Attribute: jquery removing html5 required attribute
Final code works and looks like this:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script type="text/javascript">
$(function() {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("input[type='radio']").change(function() {
$('.'+$(this).attr('name')).each(function(index) {
$(this).removeAttr('required');
});
if($(this).is(':checked')) {
$('.'+$(this).attr('id')).each(function(index) {
$(this).prop('required',true);
});
}
});
$('#submit').click(function() {
$(this).validate();
});
});
Back to the HTML of the document: I did a lot of subtle editing to the text by creating specific ids and names for the radio buttons that matched up with the class names for the text controls.
Here is that end result:
<body>
<form name="jp2code" action="#" method="POST">
<div>For each field below, provide the Phone Number, E-Mail Address, and Street Address. <b>Indicate the preferred contact method using the radio button.</b></div>
<fieldset>
<legend>Contact 1</legend>
<span>
<input type="radio" id="group1_Phone" name="group1"/>
<label for="group1_Phone">Phone:</label>
<input type="text" name="group1_PhoneText" class="group1 group1_Phone" />
<br/>
<input type="radio" id="group1_EMail" name="group1"/>
<label for="group1_EMail">E-Mail:</label>
<input type="text" name="group1_EMailText" class="group1 group1_EMail" />
<br/>
<input type="radio" id="group1_USMail" name="group1"/>
<label for="group1_USMail">US Mail:</label>
<input type="text" name="group1_USMailText" class="group1 group1_USMail" />
</span>
</fieldset>
<fieldset>
<legend>Contact 2</legend>
<span>
<input type="radio" id="group2_Phone" name="group2"/>
<label for="group2_Phone">Phone:</label>
<input type="text" name="group2_PhoneText" class="group2 group2_Phone" />
<br/>
<input type="radio" id="group2_EMail" name="group2"/>
<label for="group2_EMail">E-Mail:</label>
<input type="text" name="group2_EMailText" class="group2 group2_EMail" />
<br/>
<input type="radio" id="group2_USMail" name="group2"/>
<label for="group2_USMail">US Mail:</label>
<input type="text" name="group2_USMailText" class="group2 group2_USMail" />
</span>
</fieldset>
<div>
<input type="submit" value="Send" id="submit"/>
</div>
</form>
</body>
Let me explain what is going on in the jQuery, using the HTML above:
When a radio button's checked state changes, each control with a class name that matches the radio button's name attribute has the required property removed.
If a radio button is checked (i.e. checked=true), then each control with a class name that matches the radio button's id attribute has the required property added.
Finally, the validator seems to have to be run on a single form control (not on individual text controls like I was doing).
Here is the sample Fiddle that I ended with: Fiddle v8
At tilda: You didn't say much, but what you did say helped a lot!

jQuery Radio Button function not working properly

I have a form with two radio buttons and a submit button which leads to a specific form based upon the user's selection.
I wanted to use jQuery to change between the two buttons but have gotten myself a bit lost.
Here is my javascript from another file in the proj:
function goTo()
{
var yesButton = $('#yesRad');
var noButton = $('#noRad');
if (yesButton[0].checked)
{
submitForm('yesForm') && noButton.Checked==false;
}
else (noButton[1].checked)
{
submitForm('noForm') && yesButton.Checked==false;
}
Inside the jsp I have the following code:
<form:form action="interested" commandName="user" name="yesForm" id="yesForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
<input type="hidden" name="mode" value="1" />
<input type="radio" name ="radio"id="yesRad" value="yesForm" checked="checked" />Yes<br>
</form:form>
<form:form action="notinterested" commandName="user" name="noForm" id="noForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
<input type="hidden" name="mode" value="1" />
<input type="radio" name="radio" id="noRad" value="noForm" />No<br>
</form:form>
Submit
<script>
$("#yesRad").change(function(){
var $input = $("#yesRad");
var $inputb = $("#noRad");
if($inputb.is(':checked'))
$("#yesRad").prop("checked", false);
else if($input.is(':checked'))
$("#yesRad").prop("checked",true) && $("#noRad").prop("checked",false);
});
</script>
I have gotten some functionality out of my jQuery but it's definitely far from correct..
I hope I was clear and thorough in my question. Thanks in advance!!
To begin with, don't use prop, use attr. prop is slower.
You've defined variables so let's not look them up again. In your if/else statement just use the variables.
I'm not entirely sure what you're trying to do with the &&. I suspect you're trying to set the value of the two inputs. If so, they should be separate statements. If inputb is checked there is no reason to set it to checked, so we can remove that piece.
You probably want this change to fire on both inputs.
$("#yesRad, #noRad").change(function(){
var $input = $("#yesRad");
var $inputb = $("#noRad");
if($inputb.is(':checked')){
$input.attr("checked", false);
} else if($input.is(':checked')){
$inputb.attr("checked",false);
}
});
Solved: Using javascript and taking the radio buttons out of the separate form elements.
First let's take a look at the JSP form elements involved:
<form:form action="interested" commandName="user" name="yesForm" id="yesForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
</form:form>
<form:form action="notinterested" commandName="user" name="noForm" id="noForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
</form:form>
<input name="radio" type="radio" id="Yes" value="yes" />Yes<br>
<input name="radio" type="radio" id="No" value="no"/>No<br>
What I did here was simply take the radio buttons out of the separate forms and grouped them together...pretty obvious; now let's look at the javascript file.
function goHere()
{
var yesButton = $('#Yes');
var noButton = $('#No');
var str ="Please select an option first then press the 'Submit' button";
if (yesButton[0].checked)
{
submitForm('yesForm');
}
else if (noButton[0].checked)
{
submitForm('noForm');
}
else
{
document.write(str.fontcolor.font("red"));
}
}
As you can see the function 'goHere();' is going to tell the submit button in the following code where we want to go based on the user's selection on our radio buttons.
Here's the call from our javascript function in a submit button on the form...
<div class="button-panel" id="Submit"><span class="buttons buttons-left"></span>
<button type="button" class="buttons buttons-middle" name="submitBtn" onClick="goHere();">Submit</button>
<span class="buttons buttons-right"></span>
That's it!! Simply put; sometimes, while it's invaluable to learn something new, if it's not broke--etc. Hope this helps someone later on down the line!

Categories