I am stuck with a problem. I want to add call functions based on selection in radio button. But one of radio buttons doesn't work at all (not calling the function), other is not checked when clicked. Here is my code:
function clearElement(element_id){
document.getElementById(element_id).remove();
}
function createCheck(){
if (!document.getElementById('check')){
var btn = "<button onclick=\"checkData()\" id='check'>Check</button>";
document.getElementById("added").innerHTML += btn;
}
}
function addElements(){
var added0 = "<p>Choose the filling method:</p><br>";
var added1 = "<input type=\"radio\" value='Auto' id='auto' name=\"auto_manual\">I have ID</input>";
var added2 = "<input type=\"radio\" value='Manually' id='manual' name=\"auto_manual\"> Enter data manually</input><br>";
var added3 = "<p>Identification Code</p><br><input type=text id='ID'><br>";
var added4 = "<p>Enter your email address:</p><br><input type='email' id='mail' autocomplete=\"on\"></input><br>";
var added5 = "<button onclick=\"fillIn()\">Continue</button>";
document.body.innerHTML += "<div id=\"added\">" + added0 + added1 + added2 + added3 + added4 + added5 + "</div>";
var f0 = document.getElementById('auto');
var f1 = document.getElementById('manual');
f0.onclick = function() { createCheck();};
f1.onclick = function() { clearSelect('check');};
}
I want it to work the following way: if a user chooses "I have ID" option, the radio button is checked and the button "Check" will be created. If "Enter data manually", the button "Check" will disappear if exists.
Could you, please, help me with it?
Update (HTML):
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<title>Demo Web App</title>
</head>
<body>
<h1>Template Creator Bot</h1> <br> <br>
<script>
...
</script>
<div id='change'>
<select name="docs" id="selectedTemplate">
<option value="Order">Order</option>
<option value="Complaint">Complaint</option>
<option value="Other">Other</option>
</select>
<button onclick="addElements()">Next</button>
</div>
</body>
</html>
It would be better if you made the button element once and just toggled its visibility on demand.
There are also better strategies to compose dynamic html on your DOM instead of using innerHTML like using <template> or creating elements with document.createElement().
By the way, addressing specifically your issue here, I made a demo that adds the button in the main addElements() routine, and two functions: showButton() and hideButton() that will be called by the click event handlers added to the two radio options.
addElements();
function showButton(){
const target = document.getElementById('check');
if (target.classList.contains('hide'))
target.classList.remove('hide');
}
function hideButton(){
const target = document.getElementById('check');
if (!target.classList.contains('hide'))
document.getElementById('check').classList.add('hide');
}
function addElements(){
var added0 = "<p>Choose the filling method:</p><br>";
var added1 = "<input type='radio' value='Auto' id='auto' name='auto_manual'>I have ID</input>";
var added2 = "<input type='radio' value='Manually' id='manual' name='auto_manual'>Enter data manually</input><br>";
var added3 = "<p>Identification Code</p><br><input type=text id='ID'><br>";
var added4 = "<p>Enter your email address:</p><br><input type='email' id='mail' autocomplete='on'></input><br>";
var added5 = "<button onclick='fillIn()'>Continue</button>";
var added6 = "<button class='hide' onclick='checkData()' id='check'>Check</button>";
document.body.innerHTML +=
"<div id='added'>" + added0 + added1 + added2 + added3 + added4 + added5 + added6 + "</div>";
/*
Here adding the click event listener for the two radio options..
in the rest of your generated html you used the approach of defining handlers on html
so it's not clear why here you opted to do it programmatically for the radio options..
Anyway I only slightly changed the approach using addEventListener instead.
*/
var f0 = document.getElementById('auto');
var f1 = document.getElementById('manual');
f0.addEventListener('click', function() { showButton();});
f1.addEventListener('click', function() { hideButton();});
}
.hide{
display: none;
}
input[type=radio]{
cursor: pointer;
}
Related
I'm trying to do a form field validation. I got the text fields validation working from here, but not for the radio buttons as I am unsure of where I did wrong.
HTML:
<div>
<label>Gender:</label>
<input type="radio" name="gender" class="gender" value="Female" >Female</input>
<input type="radio" name="gender" class="gender" value="Male" >Male</input> <br/>
<span class="error">This field is required</span>
</div>
jQuery:
$('.gender').on('input', function() {
var input = $( this );
var is_checked = $("input[name=gender]:checked").length != 0;;
if (is_checked) {$('.gender').removeClass("invalid").addClass("valid");}
else {$('.gender').removeClass("valid").addClass("invalid");}
});
This is the real-time validation code which I played around on. It does not work however. When submitting the form, my error message still shows up regardless of which radio button I choose.
$("#studentsform").submit(function(event) {
var form_data = $("#studentsform").serializeArray();
var error_free = true;
for (var input in form_data){
var element = $("#"+form_data[input]['name']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid) {error_element.removeClass("error").addClass("error_show"); error_free = false;}
else {error_element.removeClass("error_show").addClass("error");}
}
if (!error_free) {
event.preventDefault();
}
else {
idcount++
var Surname = $('#surname').val();
var Name = $('#name').val();
var Gender = $('.gender:checked').val();
var Addr = $('#address').val();
var Email = $('#email').val();
var Phone = $('#phone').val();
$("#tblData tbody").append( "<tr>"+ "<td>" + idcount + "</td>"+ "<td>" + Surname + "</td>"+
"<td>" + Name + "</td>"+
"<td>" + Gender + "</td>"+
"<td>" + Addr + "</td>"+
"<td>" + Email + "</td>"+
"<td>" + Phone + "</td>"+
"<td><button class='btnEdit'>Edit</button><button class='btnDelete'>Delete</button></td>"+ "</tr>");
$(".btnEdit").bind("click", Edit);
$(".btnDelete").bind("click", Delete);
}
});
After checking all real-time validation, on the submit button I do the code above, which is to double check for validations and if it is error free, i append all the inputs into a row.
Preview:
As you can see from the picture above, even after clicking on Insert, my error message still shows up.
The author's code are very structured, but if anyone has a better and simpler way, could you please provide me a sample solution?
Much thanks!
Looks like you need
$("input[name=gender]").prop("checked");
which will return a boolean matching the checked value
Edit:
If you want to keep your code the same, you need to add the .valid class to all the gender-classed inputs. This way, when you check one radio, it will make both valid, and you shouldn't get an error.
$('.gender').on('input', function() {
var input = $( this );
var is_checked = $("input[name=gender]:checked").length != 0;
if (is_checked){
$('.gender').removeClass("invalid").addClass("valid");
} else {
$('.gender').removeClass("valid").addClass("invalid");
}
});
Everytime a user add a certain employee using a dropdownlist, It will be added and displayed. Here is my code.
<p id="employeeData"></p>
<center>
#Html.DropDownList("employee")
<input type="button" value="Add" onclick="insertNew();" />
</center>
<script type="text/javascript">
function insertNew() {
var emp_data = [];
//getting the selected value
var emp_name = document.getElementById("employee");
var selected_value = emp_name.options[emp_name.selectedIndex].value;
var selected_text = emp_name.options[emp_name.selectedIndex].text;
// getting the id where to show the output
var messageBox = document.getElementById("employeeData");
emp_data.push(selected_text);
messageBox.innerHTML = "";
messageBox.innerHTML += " " + emp_data + "<br/>";
}
</script>
But then, the output I was expecting was not achieve. Only the current selected data will be displayed and the previous one was replaced.
Any Ideas?
Thanks.
I'm really new in javascripting...(my webpage is based on jsp)
I'm trying to generate input box when option from select box is selected...
When user select any input from select box, it will send value to function init() and generate input boxes based on the value...
For example: if
<option value="IP,OS" name="sysl"><%=sysname%></option>
is selected..then it should generate something like
<tr>
<td> Enter IP:</td>
<td><input type="text" id="IP" name="IP"></td>
</tr>
<tr>
<td> Enter OS:</td>
<td><input type="text" id="OS" name="OS"></td>
</tr>
But my code does doesn't generate any...
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<title>Run Batch Script</title>
<script type="text/javascript">
function init() {
document.getElementById("bname").addEventListener("change", function(){
var value = document.getElementById("bname").value; // this gives you the selected value.
var split = value.split;
var splitsize = split.length;
for (var j=0; j<splitsize; j++){
var a = "<input type = 'text' name = '" + split[j] + "' id = '" + split[j] + "'>";
document.getElementById("inputBox").innerHTML = a;
}
// Your code to add the element that you need.
}
)};
</script>
<body>
<form action="./run?host=<%=host%>&envname=<%=envname%>" method="post" name="batchForm">
<table border="0">
<tr style="font-weight: bold; font-size: 16px;">
<td>System Name: </td>
</tr>
<tr>
<td>Select Batch : </td>
<td><select id="bname" name="bname" onclicke="init()">
<%
String src = "";
String[] temp;
String loc = root + "\\" + "Temp.txt";
int c;
int tempsize;
String param;
BufferedReader S = new BufferedReader(new FileReader(loc));
ArrayList<String> list = new ArrayList<String>();
while ((src = S.readLine()) != null){
c = 3;
param = "";
temp =src.split(":");
tempsize =temp.length;
list.add(temp[0]);
if ((tempsize >2)){
int i;
for (i=2; tempsize>i ; i++){
if((temp[i].equals("null"))){
param = "";
}
else if ((i ==2) && (temp[i] != "null")){
param = temp[i];
}
else if ((i > 2)){
param = param + "," + temp[i];
}
}
}
%>
<option value="<%=param%>" name="<%=temp[0]%>"><%=temp[0]%></option>
<%
}
BatchS.close();
%>
</select></td>
</tr>
<div id = "inputBox"></div>
What did I do wrong?
Thanks in advance!
There is some confusion about the event registration of your tag. As you said your are new to javascript, I think that it worth some explanation about event registration.
You have two ways to register some event in your HTML tag.
Using some onSomething attribute, for example:
<select onclick="myFunction()"/>
The other way, is to register the event handler using javascript:
document.getElementById("sysinfo").addEventListener("click", function(){...});
Both will work. However, in the first example the handler will be registered for you automatically when the page loads. The second way, the handler must be registered manually.
In your code you are trying to mix both.
You can either use the tag event registration, and the event is onchange (not onselect as pointed by David). OR you will have to call the init() function when the page loads. One way to do that is by putting the following code at the end of your HTML to register your event when page loads.
<script type="text/javascript">
init();
</script>
In summary I would do:
<script type="text/javascript">
function writeInputs() {
alert('writing inputs'); //helps checking if the handler is ok .. comment this when done
var value = document.getElementById("sysinfo").value; // this gives you the selected value.
var split = value.split;
var splitsize = split.length;
var code = '';
for (var j=0; j<splitsize; j++){
var a = "<input type = 'text' name = '" + split[j] + "' id = '" + split[j] + "'>";
code += a;
}
document.getElementById("inputBox").innerHTML = code;
}
</script>
<select id="sysinfo" name="sysname" onchange="writeInputs()">
The javascript is already corrected with a solution to the problem pointed by JB Nizet. I have not tested the code so there can be other problems
I want to add some html data to the end of a div container.
Currently, I do it with using innerHtml:
<script language="javascript">
var addid = 0;
function addInput(id){
var docstyle = document.getElementById('addlist').style.display;
if(docstyle == 'none')
document.getElementById('addlist').style.display = '';
addid++;
var text = "<div id='additem_"+addid+"'><input type='text' size='100' value='' class='buckinput' name='items[]' style='padding:5px;' /> <a href='javascript:void(0);' onclick='addInput("+addid+")' id='addlink_"+addid+"'>add more</a></div>";
document.getElementById('addlist').innerHTML += text;
}
</script>
<div id="addlist" class="alt1" style="padding:10px;">
New list items are added to the bottom of the list.
<br /><br />
</div>
The problem is that the value that was entered in the input fields is removed once another input field is added.
How can I add content without and keep the entered data?
PS: I do not use jquery.
innerHTML changes reset form elements. Instead use appendChild. See this demo http://jsfiddle.net/5sWA2/
function addInput(id) {
var addList = document.getElementById('addlist');
var docstyle = addList.style.display;
if (docstyle == 'none') addList.style.display = '';
addid++;
var text = document.createElement('div');
text.id = 'additem_' + addid;
text.innerHTML = "<input type='text' value='' class='buckinput' name='items[]' style='padding:5px;' /> <a href='javascript:void(0);' onclick='addInput(" + addid + ")' id='addlink_" + addid + "'>add more</a>";
addList.appendChild(text);
}
Take a look at this http://reference.sitepoint.com/javascript/Node/appendChild
So something like
document.getElementById('addlist').appendChild(text);
i am using this code to access all the hidden elements from a form:
function get_hidden_val(ids,form_id)
{
var get_check_val = document.getElementById(ids);
if(get_check_val.checked){
var div = $('<div></div>')
.appendTo('form#bulk_add_cart')
.attr('id',"bulk_"+form_id)
$("form#" +form_id).find('input[type="hidden"]').each(function(){
var value =$(this).val();
var name = $(this).attr("name");
var tags = "<input type='hidden' value='" + value + "' name='"+name+"'>";
$('div#' +form_id).append(tags);
});
}
else
{
$("form#bulk_add_cart").find('div#' +form_id).remove();
}
}
My problem is when I click the first checkbox it give me the result but when i click the second checkbox it doesn't and also the another problem is when i click first checkbox it shows total hidden elements but when i second time checked it, it show 4 less ?
Please suggest a solution.
Thanks
#user704302: Missing >, update var tags to --
var tags = "<input type='hidden' value='" + value + "' id='"+id+"'>";