Function is not working on radio button onclick - javascript

JavaScript function (here f1()) is not getting called on radio button (here id=iprange) onclick event.
HTML
function f1() {
alert('yes');
}
<form role="form">
<div class="box-body">
<label>
<input type="radio" name="optionsRadios" id="fullscan1" value="option1" /> Full Scan
</label>
<!-- "IP Range" is the radio button that should show a "yes" alert. -->
<label>
<input type="radio" name="optionsRadios" id="iprange" value="option2" onclick="f1();" /> IP Range
</label>
From:
<input type="text" id="text1"> To:
<input type="text" id="text2">
<label>
<input type="radio" name="optionsRadios" id="subnet" value="option3" /> Subnet
</label>
<input type="text" id="text3">
<button class="btn btn-danger">Scan</button>
</div>
</form>

#Suresh Kota . At this point its impossible to give an satisfying answer, you'll have to do a step-by-step-investigation. Start with following and post your result here.
<head>
....
<script> // your script tag, I assume it looks like this
$(document).ready(function() {
/* some code */
});
// now include your function as last line outside document ready
function f1() {alert('yes');};
</script>
<!-- Make sure this is the only script tag in your html -->
....
</head>
If that doesn't help, rename your function, e.g. function xxx() {alert('yes');};
and same with onclick-attribute in input-tag: onclick="xxx()".
When having no succes, try directly: onclick="alert('yes')"
If that all not work, there's something inside your document.ready that manipulates the button, and you should post that code.

Try this one:
<input type="radio" name="optionsRadios" onclick="handleClick(this);" value="option1" />
<input type="radio" name="optionsRadios" onclick="handleClick(this);" value="option2" />
...
<script>
function handleClick(myRadio) {
alert('New value: ' + myRadio.value);
}
</script>

<label onclick="red()"><input type="radio" name="colors" id="red">Red</label>
or
<label onclick="red()"><input type="radio" name="colors" id="red"></label>
<label for="red">Red</label>
<script>
function red(){
alert('i am red');
}
</script>
if you want to call onclick function on radio button then you can use like this, it will work for you
Note: we have to call on function on label instead of radio button

Related

How do I add two getElement and a submit button to make one If Statment?

Sumary: I am looking for away to add two seperate getElementbyId and a submit button to an If Statment in order to make it run.
HTML Example:
<form>
<div>
<fieldset id="group1">
<input type="radio" name="type" id="h" value="1111" onclick="func2();" />0 Human</br>
<input type="radio" name="type" id="r" value="2222" onclick="func2();" />1 Robot</br>
<input type="radio" name="type" id="a" value="3333" onclick="func2();" />2 Animal</br>
</fieldset>
</div>
<div>
<fieldset id="group2">
<input type="radio" name="type" id="c" value="1111" onclick="func2();" />4 Jerry</br>
<input type="radio" name="type" id="b" value="2222" onclick="func2();" />5 Xr10Zbot</br>
<input type="radio" name="type" id="z" value="3333" onclick="func2();" />6 Girrafe</br>
</fieldset>
<p><input style="width: 60px;" type="submit" name="type" id="f" class="7" value="submit" onclick="func()2;" /></p </div>
</form>
JavaScript Example:
<script>
function func2()
{
if(document.getElementById("h").checked)
// I want for the if statment to require you to also have to check c and click submit to run
{
var val = document.getElementById("h").value;
alert(val);
}
else if(document.getElementById("r").checked)
{
var val = document.getElementById("r").value;
alert(val);
}
else if(document.getElementById("a").checked)
{
var val = document.getElementById("a").value;
alert(val);
}
}
</script>
What I need the if statment to run:
Make it to wher you have to click two radio buttons and submit to run the alert
if(document.getElementById("h").checked) + (document.getElementById("c").checked) + (document.getElementById("f"))
I don't fully understand what you want to do. I hope my solution will help you.
Issue 1
There is a typo in the submit button.
❌NG onclick="func()2;"
✅OK onclick="func2();"
Issue 2
Radio buttons with the same name attribute belong to one group. Therefore, only one of the six buttons can be turned on. One of the buttons in #group1 and one of #group2 are not turned on at the same time. Change name.
For example,
<fieldset id="group2">
<input name="type2">
<input name="type2">
<input name="type2">
</fieldset>
Issue 3
I think it is a bit difficult to use func2() for all buttons including the submit button. I recommend making another function for it.
My solution
This JS doesn't work properly here on the embed snippet. Please copy, paste and run it on an actual editor such as Visual Studio Code.
// Get DOMs
var elementC = document.getElementById('c');
var submitButon = document.getElementById('f');
// Get #group1 radio buttons at once
var group1Buttons = document.querySelectorAll('#group1 [type="radio"]');
// These are needed in If statements
// var elementH = document.getElementById('h');
// var elementR = document.getElementById('r');
// var elementA = document.getElementById('a');
function func2(e) {
e.stopPropagation();
// You may use this If statement
// if (elementH.checked) {
// alert(elementH.value);
// } else if (elementR.checked) {
// alert(elementR.value);
// } else if (elementA.checked) {
// alert(elementA.value);
// }
// I prefer this one because it's shorter.
alert(this.value);
}
function func3(e) {
e.stopPropagation();
if (!elementC.checked) {
e.preventDefault(); // Stop submitting
alert(`You need to check ${elementC.getAttribute('data-text')}!!`);
}
}
// When one of the radio buttons is clicked, executes func2()
group1Buttons.forEach(radio => radio.addEventListener('click', func2, false));
// When the submit button is clicked, executes func3()
submitButon.addEventListener('click', func3, false);
<form>
<div>
<!-- Removed onClick="func2()" -->
<!-- Added required to one of radio buttons -->
<fieldset id="group1">
<input type="radio" name="type" id="h" value="1111" required />0 Human</br>
<input type="radio" name="type" id="r" value="2222" />1 Robot</br>
<input type="radio" name="type" id="a" value="3333" />2 Animal</br>
</fieldset>
</div>
<div>
<!-- Removed onClick="func2()" -->
<!-- Added required to one of radio buttons -->
<!-- Change name: type => type2 -->
<!-- Added data-text attribute -->
<fieldset id="group2">
<input type="radio" name="type2" data-text="4 Jerry" id="c" value="1111" required />4 Jerry</br>
<input type="radio" name="type2" id="b" value="2222" />5 Xr10Zbot</br>
<input type="radio" name="type2" id="z" value="3333" />6 Girrafe</br>
</fieldset>
<!-- Removed onClick="func2()" -->
<p><input style="width: 60px;" type="submit" name="type" id="f" class="7" value="submit" /></p>
</div>
</form>

Radio button value selector

I am trying to write a form. In the form there will be one set of radio buttons. When I open my html page on my browser, I would like to click one of the buttons and then write its value in a text after I click a submit button.
This is part of the form code:
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd><input type="radio" checked="checked" name="tb" value="1"/>
block
<input type="radio" name="tb" value="2" />
dark
<input type="radio" name="tb" value="3" />
f1b
<input type="radio" name="tb" value="0" />
custom
<p></p>
</dl>
</form>
And this is part of my javascript code:
function buildData(){
var txt =
"type = " + ($("[name='tb']").is(":checked") ? "block" :
($("[name='tb']").is(":checked") ? "dark" :
($("[name='tb']").is(":checked") ? "f1b" : "custom")))
return txtData;
}
$(function(){
// This will act when the submit BUTTON is clicked
$("#formToSave").submit(function(event){
event.preventDefault();
var txtData = buildData();
window.location.href="data:application/octet-stream;base64,"+Base64.encode(txtData);
});
});
But it is currently not working properly (it won't save the right selection in txt).
How can I fix it? Thanks in advance
UPDATE:
From one of the answers:
function buildData(){
var txtData =
"some text... " + $("[name=tipoBooster]").change(function() {
var txt = ["custom","block","dark","f1b"][this.value];
console.log(txt);
}) + "other text...";
return txtData;
}
Here is a simple solution for getting user input when the user changes the checked radio button
$("[name=tb]").change(function() {
var txt = ["custom","block","dark","f1b"][this.value];
console.log(txt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd><input type="radio" checked="checked" name="tb" value="1"/>
block
<input type="radio" name="tb" value="2" />
dark
<input type="radio" name="tb" value="3" />
f1b
<input type="radio" name="tb" value="0" />
custom
<p></p>
</dl>
</form>
but in your case you need to edit the build function to be like this
function buildData(){
return "type = " + ["custom","block","dark","f1b"][$("[name='tb']:checked").val()];
}
Or if you want more flexible solution you can add labels to your inputs
like this
$("[name='tb']").change(function() {
console.log($(this).parent().text().trim());
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd>
<label><input type="radio" name="tb" value="1" checked="checked" />block</label>
<label><input type="radio" name="tb" value="2" />dark</label>
<label><input type="radio" name="tb" value="3" />f1b</label>
<label><input type="radio" name="tb" value="0" />custom</label>
</dd>
<p></p>
</dl>
</form>
this was for a change event but your build function should be like this then
function buildData() {
return $("[name='tb']:checked").parent().text().trim();
}
Explanation:
$("[name='tb']:checked") gets the checked radio input element
.parent() gets its parent since we need the label to get its text
.text() gets the text of the label
.trim() removes white space before and after the text
Your selector is referencing an id not the name attribute. Try this instead.
var txt =
"type = " + ($("[name='tb']").is(":checked") ? "block" :
($("[name='tb']").is(":checked") ? "dark" :
($("[name='tb']").is(":checked") ? "f1b" : "custom")))
You could use: $("[name='tb']").val() and just set the corresponding values on the actual radio buttons to block dark etc.
e.g:
<input type="radio" checked="checked" name="tb" value="block"/>
block
<input type="radio" name="tb" value="dark" />
dark
<input type="radio" name="tb" value="f1b" />
f1b
<input type="radio" name="tb" value="custom" />
custom
A # in a jQuery selector is for selecting by id attribute.
What if you change the selector from ($("#tb").is(":checked")... to a name selector.
e.g.
($("input[name*='tb']").is(":checked")
If you just want to get the selected radio button's text. Could you update the html to be.
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd>
<input id="option1" type="radio" checked="checked" name="tb" value="1"/>
<label for="option1">block</label>
...
<p></p>
</dl>
</form>
Then your function can just return the selected text
function buildData(){
return "type = " + $("input[name*='tb']").is(":checked").next("label").text();
}
If you don't want to add labels to the html, then I would try $("input[name*='tb']").is(":checked").next().text();
Maybe sharing a minimum working example link would help, as I am just writing the above from memmory, referencing the documentation (https://api.jquery.com/text/#text).

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/>

How to check if all the radio buttons are selected or not?

Well I am trying to build a web page that has set of radio buttons. I am using jquery to check if all the radio buttons are checked or not. Here is the code:
<body>
<p class="Cal">Welcome,</p>
<hr />
<p class="Radio1">Answer the questions below. You will find the results after clicking 'Check my score'.</p>
<hr />
<form method="post">
<p class="Question">1. Do you sleep early at night? (Anywhere around 9-10pm)</p>
<p>
<label>
<span class="Radio">
<input type="radio" name="RadioGroup1" value="Yes" id="RadioGroup1_0" />
</span></label>
<span class="Radio"> Yes
<br />
<label>
<input type="radio" name="RadioGroup1" value="No" id="RadioGroup1_1" />
No
</label>
<br />
<label>
<input type="radio" name="RadioGroup1" value="Sometimes" id="RadioGroup1_2" />
Sometimes </label>
</span><br />
</p>
<p class="Question">2. Do you wake up early in morning?(Anywhere around 5-7am)</p>
<p>
<label>
<span class="Radio">
<input type="radio" name="RadioGroup2" value="Yes" id="RadioGroup2_0" />
Yes </span></label>
<span class="Radio"><br />
<label>
<input type="radio" name="RadioGroup2" value="No" id="RadioGroup2_1" />
No
</label>
<br />
<label>
<input type="radio" name="RadioGroup2" value="Sometimes" id="RadioGroup2_2" />
Sometimes
</label>
</span><br />
</p><input type="submit" value="Check my score" /></form></body>
Well there are 30 such questions. And my jquery code is as follows:
$(document).on('submit', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.Radio').each(function () {
// Question text
var Question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(Question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
else{
msg = "Done!";
alert(msg);
}
return validate;
});
Now I tried all ways possible to make this work. But even after I check radio button for each answer I keep on getting the popup saying "Please answer the following questions:" and then a blank list. I never get the message "Done!" even though answer for all the questions are checked.
Where is the fault?
You can use the HTML5 required attribute, which is better option.
You can also use JavaScript loop and retrieve the value from each radio group, using
$("input:radio[name=radiogroupX]:checked")

Get radio button value which is outside a form post

I have a form which has some radio buttons which is outside this form.The html is as follows
<input type="radio" id="radio1" name="radios" value="radio1" checked>
<label for="radio1">Credit Card</label>
<input type="radio" id="radio2" name="radios"value="radio2">
<label for="radio2">Debit Card</label>
<form method="post" action='./process.php'>
<label>name</label>
<input type="text"/>
<input type="submit" style="float:right" value="Pay Now"/>
</form>
When I press on the paynow button,i want to pass the value of button selected to the php of this form (process.php) .But I dont want to place the radio buttons inside the form.Is there any solution?
You could have a hidden value inside the form, onsubmit put the value of that radio button inside the hidden value
<input type="radio" name="test" value="a">a<br>
<input type="radio" name="test" value="b">b
<form>
<input type="hidden" name="test" id="hidden">
<submit onClick="transferData">
</form>
<script>
var transferData = function() {
var radioVal =$('input:radio[name=test]:checked').val()
$('#hidden').val(radioVal);
}
</script>
HTML5 supports an attribute called "form". You can use it to set the form for controls that are outside your form, like so:
<input type="radio" id="radio1" name="radios" value="radio1" checked>
<label form="myForm" for="radio1">Credit Card</label>
<input type="radio" id="radio2" name="radios"value="radio2">
<label form="myForm" for="radio2">Debit Card</label>
<form id="myForm" method="post" action='./process.php'>
<label>name</label>
<input type="text"/>
<input type="submit" style="float:right" value="Pay Now"/>
</form>
Note how id="myForm" is added to the form and form="myForm" is added to the radio-buttons. Hope that helped you.
Yeah, you could add a reference to jQuery, before the </body>. Then, using JQuery, you could select the checked radio button as follows:
var selected = $("input[type='radio']:checked");
if (selected.length > 0) {
selectedVal = selected.val();
}
The selectedVal parameter will hold the value you want.
The selection of the selected radio button should be done on the click event of submit button.
That could be done as follows:
$("input[type='submit']").click(function(){
// code goes here.
});
You must have a onsubmit attribute on your form, and inside, assign to a hidden field the selected radio button value.
Like this:
<form id='myForm' method="post" action='./process.php' onsubmit='getRadioButtonValue()'>
...
<input type="hidden" name="selectedRadioValue" />
</form>
function getRadioButtonValue(){
var radioValue = $('input[name=radios]:checked', '#myForm').val();
$('input[name='selectedRadioValue']').val(radioValue);
}
Put everything in the form. If you want to send all values. Add required attibute to your tags.
Other wise use jquery
<form id="test" method="POST">
<input type="text" id="name" required minlength="5" name="name"/>
<input type="password" id="pw" required name="pw"/>
<input id ="sub" type="submit"/>
</form>
<ul id="answer"></ul>
</body>
<script>
$("#sub").click(function(event){
event.preventDefault();
query = $.post({
url : 'check_ajax.php',
data : {'name': $('input[name=name]').val(), 'pw': $('#pw').val()},
});
query.done(function(response){
$('#answer').html(response);
});
});
</script>
All you need to do is to add the value of the option/input outside the form in the data
Use this onsubmit event!
$('input[name=radios]:checked').val()
Check the example

Categories