How to identify the checked radio button by using getElementsByName? - javascript

I have a form fontVortMetodo, which I declared as
var fM = document.forms["fontVortMetodo"];
The user has the choice to submit the form to one of three PHP pages. I let him make the choice first by radio buttons with the name select. Then he should press a button, which fires the result of the form elements to the selected page.
For this firing I used the function
function destinu() {
if (fM.elements("select")[0].checked) {
fM.action = "private_php/Zamenhofa.php";
} else if (fM.elements("select")[1].checked) {
fM.action = "private_php/intereuropeco.php";
} else if (fM.elements("select")[2].checked) {
tutm = true;
fM.action = "private_php/tutmondeco.php";
}
}
There was this error:
TypeError: fM.elements("select")[0].checked is not a function".
Maybe I should try
var destiny = getElementsByName("select")
and then proceed with if (destiny[0].checked) or if (destiny[0].checked == true).
I don’t know jQuery, which somebody advised me to use, and also for JavaScript I have no reference text. Where can I find a good tutorial for jQuery, although I prefer to do everything by using JavaScript pure?

Using pure JS
Use dataset attribute to store the action.
Use this selector [name="select"]:checked to get the checked radio button.
document.querySelector('button').addEventListener('click', function(e)  {
e.preventDefault();
var checked = document.querySelector('[name="select"]:checked');
var action = checked.dataset.action;
var form = document.querySelector('#fontVortMetodo');
form.setAttribute('action', action);
var tutm = checked.dataset.tutm !== undefined;
console.log("Action: " + action);
console.log('Is tutm: '+ tutm);
//$form.submit(); // This is if you need to to submit the form.
});
<form id='fontVortMetodo' name='fontVortMetodo'>
<input type='radio' name='select' data-action="private_php/Zamenhofa.php">
<input type='radio' name='select' data-action="private_php/intereuropeco.php">
<input type='radio' name='select' data-action="private_php/tutmondeco.php" data-tutm='true'>
<button>Submit</button>
</form>

Related

getting the value of a textbox when user enters the name/id of the field

Using jquery to get the value of a textbox.
BUT
i need to enter the id of the textbox, then use that value to get the value of the textbox using jquery.
var tt = $("#fieldname").val()
that works
now how do i enter the fieldname at runtime, and get jquery to execute the val command as if it was hard coded?
There are a few ways that you could do this. One way is to listen to one of the keyboard or change events on the textbox you enter the id into, to help determine when the input has changed. So for example
$("#inputText").on("keyup", function(keyupEvent){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
});
Or another way could be to use a click event with similar kind of logic, so for example
$("#clickMe").on("click", function(){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
})
An example for the use case of both can be seen here https://fiddle.jshell.net/xpvt214o/114584/
Here is an example for you to get started with:
<body>
<p>Type "one" or "two" below</p>
<input id="search" />
<input id="one" value="This input is #one" />
<input id="two" value="And this is #two" />
<p id="result">No input specified</p>
</body>
And the corresponding jQuery code:
// Cache jQuery elements for performance and readability
var $search = $("#search");
var $result = $("#result");
$search.on("change", function() {
var search_value = $search.val();
if (search_value.length) {
search_value = "#" + search_value.toLowerCase().trim(); // Sanitise user input
if ($(search_value).length) {
$result.text($(search_value).val());
} else {
$result.text("Input not found");
}
} else {
$result.text("No input specified");
}
});
This will show the value of the specified input, if it exists.
You can see it in action here: https://jsfiddle.net/jeevantakhar/xpvt214o/114558/

Disable Button Until Fields are Full Pure JS

Trying to keep a button disabled until the form fields are filled in and I cannot seem to accomplish this. I've created a small example with a single field but the principle will be the same with a larger form.
Can anyone help?
Code:
function checkForm() {
var name = document.getElementById("name").value;
var cansubmit = true;
if (name.value.length == 0) {
cansubmit = false;
}
if (cansubmit == false) {
document.getElementById("submitbutton").disabled = true;
}
};
<input type="text" id="name" onkeyup="checkForm()" />
<button type="button" id="myButton">Test me</button>
There are a couple of mistakes in your sample:
var name is assigned to the value string of the name element, then you check the value property of that - the string has no value property.
the id of the submit button is myButton so use that id to get it by id (when setting the disabled attribute).
You can disable the submitbutton until the length of the name input is greater than 0.
And disabling the button initially sounds like a good idea, right?
See corrected example below:
function checkForm()
{
var name = document.getElementById("name").value;
var cansubmit = (name.length > 0);
document.getElementById("myButton").disabled = !cansubmit;
};
<input type="text" id="name" onkeyup="checkForm()" />
<button type="button" id="myButton" disabled="disabled">Test me</button>
You might also want to consider handling change via methods other than keypress - e.g. mouseup, etc... I tried adding onchange="checkForm()" and it works but only on blur (focus-change)...

Get / catch a button value before sending form, for form confirmation

I just want to ask the user to confirm their choice before sending a form. So I need the text value (by that I mean the innerHTML, not the value="" attribute) they have just selected/clicked for them to confirm.
The form consists of many buttons with the same name but different values (dynamically generated), so I need to "catch" it once it has been selected.
The html looks like this:
<form id="myForm" method="post" action="here.php">
<button class="bc" value="v1">foo</button>
<button class="bc" value="v2">bar</button>
</form>
I have this piece of code so far but I can't figure out how to get the value, to add it to the confirm box.
$('form#valueSelect').submit(function( event ) {
var sel = this;
var c = confirm("You have selected " + sel + " Click OK to continue?");
return c;
});
I get [object HTMLFormElement] instead of the value. I tired var sel = this.value; and value() and val and val() but it doesn't work, I don't know why.
Try to have global variable and then update it when button click. You will have then recent button clicked value in it.
var btnText = '';
$(document).ready(function(){
$('form#valueSelect').submit(function( event ) {
var c = confirm("You have selected " + btnText + " Click OK to continue?");
return c;
});
$("input[name='YourBtnName']").on("click",function(){
btnText = $(this).val();
});
});
Sorry my question wasn't quite clear.
I wanted the displayed value (innerHTML) of the button the user clicked (out of many other buttons), the html looks like this:
<form id="myForm" method="post" action="here.php">
<button class="bc" value="v1">foo</button>
<button class="bc" value="v2">bar</button>
</form>
I found a workaround by using the click instead of the submit:
$('button.bc').click(function( event ) {
var myForm = $('#myForm');
event.preventDefault();
var bval = this.value;
var choice = this.innerHTML;
var c = confirm("You have selected " + choice + "\nClick OK to continue?");
if(c == true) {
var input = $("<input>").attr("type", "hidden").attr("name", "token").val(bval);
$('#myForm').append($(input));
$('#myForm').submit();
}
});
and adding <input type="hidden" name="token"></input> in my form, in order to "store" the value of the clicked button.

Getting the ID of a radio button using JavaScript

Is there a way to get the ID of a radio button using JavaScript?
So far I have:
HTML
<input type="radio" name="fullorfirst" id="fullname" />
JavaScript
var checkID = document.getElementById(fullname);
console.log(checkID);
It outputs as null.
Essentially what I want to do is:
document.getElementById(fullname).checked = true;
...in order to change the radio button fullname to be checked on page load.
you should put fullname between quotes, since it's a string:
document.getElementById("fullname");
function checkValue() // if you pass the form, checkValue(form)
{
var form = document.getElementById('fullname'); // if you passed the form, you wouldn't need this line.
for(var i = 0; i < form.buztype.length; i++)
{
if(form.buztype[i].checked)
{
var selectedValue = form.buztype[i].value;
}
}
alert(selectedValue);
return false;
}
Hope this helps.
JavaScript Solution:
document.getElementById("fullname").checked = true;
Jquery Solution:
$("#fullname").prop("checked", true);

validate a dynamicnumber of checkboxes using javascript

I have some ASP code which presents any where from 1-any number of checkboxes (which are named the same) on the page. This validation does work however I think its a bit weak:
if (document.getElementById('selectedDocs').checked)
{
//this is here to handle the situation where there is only one checkbox being displayed
}
else
{
var checked = false;
var field = myForm.selectedDocs;
for(var j = 0; j < field.length; j++)
{
if(field[j].checked == true)
{
checked = true;
break;
}
}
if(!checked)
{
alert("You have not ticked any options. At least one must be selected to proceed!")
return false;
}
}
I was working with the code in the else block but this only works when there is more than one checkbox. It ignores the fact I have ticked the one single option when there is only one. So I placed the code inside the if section......Although it woks its a bit of a hack, can someone kindly improve it for me?
Thanking you...
Use:
var field = myForm.getElementsByName('selectedDocs');
This always returns a NodeList that you can iterate over.
If they are in a form and all have the same name, they can be accessed as a collection that is a property of the form. So given:
<form id="f0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
...
</form>
All the following return a reference to the form:
var form = document.getElementById('f0');
var form = document.forms['f0'];
var form = document.forms[0]; // if first form in document
and and all the following return a collection of the checkboxes named "cb0":
var checkboxes = form.cb0
var checkboxes = form['cb0'];
var checkboxes = form.elements.['cb0'];

Categories

Resources