Today, I will share two JavaScript tips with you. The reason is simple: recently, when CG was modifying a website's form and the previous Sony project, it was found that controlling the values and selection of radio buttons in HTML forms was quite frustrating, especially when using JSP. So today, I will share two JavaScript tips to solve this problem.
Problem 1: Can the radio button in each row of a table be automatically selected and have its value attribute changed after clicking on that row?
Solution: When the table row is clicked, iterate through all the radio buttons and compare the difference between the radio button's value and the selected value. Then, decide whether to select the radio button in this row.
Below is the JS code:
// Update the value of IdValue
//
function updateIdValue(obj, radioName) {
var cellText;
cellText = obj.cells[1].innerHTML.toString();
if (!radioName) return;
if (getRadioValue(radioName) != cellText) {
setCheckedValue(radioName, cellText);
}
IdValue = cellText; // Update
}
// Set the selected state of the radio button
function setCheckedValue(radioName, newValue) {
var radios = document.getElementsByName(radioName);
for (var i = 0; i < radios.length; i++) {
if (radios[i].value == newValue) {
radios[i].checked = true;
break;
}
}
}
Below is the demonstration effect:
http://www.lidaren.com/code/JsRadio.htm
Problem 2: The dynamically generated radio buttons and their corresponding values cannot be selected.
Solution: After the page is loaded, iterate through all the radio buttons and check if there is a matching value. If there is, set it as selected.
Below is the JS code:
// Modify the selected state of the checkBox in the edit page
function setRadioChecked(val, radioName) {
var radios = document.getElementsByName(radioName);
for (var i = 0; i < radios.length; i++) {
if (radios[i].value == val) {
radios[i].checked = true;
break;
}
}
}
This blog post is original content by Li Daren. Feel free to repost, but please remember to give credit.