In HTML, with JavaScript, create new radio button and its text? - javascript

I want that when the "Yes" radio button of a form (form1) is checked, a new form (form2) appears, with two radio buttons and their text "Yes" and "No". With an event "onclick" in the "Yes" button of the form1, I manage to make the new form appear, with the two radio buttons, but I cannot make their text appear. Since radio buttons do not have "innerHTML", I try to add the text either as plain text, either as "label", but it is not working.
Is it a problem in the syntax or in the logic (not possible to create text at the same time as the button)?
In my HTML body I have this:
<form id="form1">
<input type="radio" id= "form1_no" value="no" checked>
<label for = "form1_no" >No</label>
<input type="radio" id= "form1_yes" value="yes" onClick= exam()>
<label for = "form2_yes" >Yes</label>
</form>
The function exam() is:
<script type='application/javascript'>
function exam() {
var inputno = document.createElement("input");
inputno.type = "radio";
inputno.id = "form2_no";
inputno.value = "no";
inputno.onclick = function () {alert("I select No in Form 2")};
document.getElementById("form2").appendChild(inputno); // this is working
var inputyes = document.createElement("input");
inputyes.type = "radio";
inputyes.id = "form2_yes";
inputyes.value ="yes";
inputyes.onclick = function () {alert("I select Yes in Form 2")};
document.getElementById("form2").appendChild(inputyes); // this is working
// now, the code that is not working:
// 1st tentative (adding "Yes" and "No" as plain text after their radio button):
var textno = "No";
document.getElementById("form2_no").appendChild(textno);
var textyes = "Yes";
document.getElementById("form2_yes").appendChild(textyes);
// 2nd tentative (adding "Yes" and "No" as labels to their radio button):
var labelno = document.createElement("label");
labelno.for="form2_no";
labelno.innerHTML = "No";
document.getElementById("form2_no").appendChild(labelno);
var labelyes = document.createElement("label");
labelyes.for="form2_yes";
labelyes.innerHTML = "Yes";
document.getElementById("form2_yes").appendChild(labelyes);
}
</script>

Something like this works to create a button and label.
<div id="radio_home"></div>
<script>
var radio_home = document.getElementById("radio_home");
function makeRadioButton(name, value, text) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = name;
radio.value = value;
label.appendChild(radio);
label.appendChild(document.createTextNode(text));
return label;
}
var yes_button = makeRadioButton("yesbutton", "yes", "Oh yea! do it!");
radio_home.appendChild(yes_button);
</script>

Related

How do I make an onclick event for a dynamically added checkbox? (JavaScript)

I'm new to html and learning through YouTube and such. I'm writing a JavaScript which allows me to show a custom window with checkboxes and textboxes (and labels) on it. I disabled the textboxes to begin with, but I would like them to be enabled when the corresponding checkboxes are checked.
I've searched on the internet for a solution, already tried using:
document.getElementById('chb1').onclick = function() { //my function };
or
document.getElementById('chb1').onclick = //my function;
but neither of them works.
function MyCheckboxWindow()
{
this.render = function(func,titel,dialog,checktext1)
{
var dialogboxbody = document.getElementById ('dialogboxbody');
dialogboxbody.innerHTML = dialog + ': <br>';
if(checktext1 != null)
{
dialogboxbody.innerHTML +='<br><input type="checkbox" id="chb1"><label for="chb1" class="lbl" id="lbl1"></label>'
+ '<label for="txt1">€</label> <input type="text" id="txt1" value="0,00" disabled>';
document.getElementById('lbl1').innerHTML = checktext1 + ': ';
document.getElementById('chb1').onclick = alert('');
}
else if(!checkboxCheck)
{
dialogboxbody.innerHTML +='<br><input type="checkbox" id="chb1"><label for="chb1" class="lbl" id="lbl1"></label>'
+ '<label for="txt1">€</label> <input type="text" id="txt1" value="0,00" disabled>';
document.getElementById('lbl1').innerHTML = "Other: : ";
document.getElementById('chb1').onclick = Change.ischanged('chb1');
checkboxCheck = true;
}
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="CheckboxWindow.ok(\''+func+'\')">Ok</button> <button onclick="CheckboxWindow.cancel()">Cancel</button>';
}
}
var CheckboxWindow = new MyCheckboxWindow();
function CheckboxChanged()
{
this.ischanged(id)
{
alert('');
}
}
var Change = new CheckboxChanged();
Just for info, there should be 6 of these checkboxes, but I left them out in this example. Also, in the "if", I replaced my function by an alert. The code in the if-clause produces an alertbox only when I open the custom window, clicking the checkbox doesn't do anything (but tick the box).
Writing it like I did in the "else if" in this example, doesn't produce anything at all, nor does function() { Change.ischanged('chb1'); } (like I said before).
Please tell me why this isn't working. There's probably a better way of adding these checkboxes as well, so if you know any, please let me know as well.
Hope this helps as a starting point:
//Dynamically create a checkbox, and add it to a div.
//appendChild() works for other types of HTML elements, too.
var div = document.getElementById("div");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "checkbox_1";
div.appendChild(checkbox);
var textbox = document.createElement("input");
textbox.type = "text";
textbox.disabled = true; //programmatically disable a textbox
div.appendChild(textbox);
//do something whenever the checkbox is clicked on (when user checks or unchecks it):
checkbox.onchange = function() {
if(checkbox.checked) { //if the checkbox is now checked
console.log("checked");
textbox.disabled = false;
}
else {
console.log("unchecked");
textbox.disabled = true; //programmatically disable a textbox
}
}
<div id='div'></div>
Thanks for your reply and I'm sorry for responding this late, I was quite busy the past 2 weeks and didn't have a lot of time.
I've tried to use your sample code but was unable to make it work. However, I was able to get it working by adding "onclick="Change.ischanged()" to the input in the if statement. I'm sure I tried something like that before, but I probably typed "CheckboxWindow" or "CheckboxChanged" instead of "Change" by mistake.
if(checktext1 != null)
{
dialogboxbody.innerHTML +='<br><input type="checkbox" id="chb1" onclick="Change.ischanged()"><label for="chb1" class="lbl" id="lbl1"></label>'
+ '<label for="txt1">€</label> <input type="text" id="txt1" value="0,00" disabled>';
document.getElementById('lbl1').innerHTML = checktext1 + ': ';
}
I know that adding the objects like this isn't the best way, but I seem to be having trouble trying to achieve my goal in your way.
I also changed "this.ischanged(id)" to "this.ischanged = function()" (I also made it so I don't need to pass the id anymore).
Try the OnClick event instead of the OnChange event for the checkbox.
//Dynamically create a checkbox, and add it to a div.
//appendChild() works for other types of HTML elements, too.
var div = document.getElementById("div");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "checkbox_1";
div.appendChild(checkbox);
var textbox = document.createElement("input");
textbox.type = "text";
textbox.disabled = true; //programmatically disable a textbox
div.appendChild(textbox);
//do something whenever the checkbox is clicked on (when user checks or unchecks it):
checkbox.onclick = function() {
if(checkbox.checked) { //if the checkbox is now checked
console.log("checked");
textbox.disabled = false;
}
else {
console.log("unchecked");
textbox.disabled = true; //programmatically disable a textbox
}
}
<div id='div'></div>

Creating a Dynamic form with Javascript

Lets start again,
I would like to loop through a few values and then append them to a form to show a select box,
This is my button to add a new field in HTML:
<input type="button" value="Add Field" onclick="addField()">
Then the addField Javascript:
function addField() {
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('name', "newDrop[]");
input.setAttribute('id', 'newDrop');
input.setAttribute('class', 'newDrop');
input.setAttribute('placeholder', 'Options');
document.getElementById('dropdown').appendChild(input);
};
As you can see that this will append a new form with the attributes above.
Once I am happy with the values in each field and submit the additional fields with the below HTML:
<input type="button" value="Create Field" onclick="addInput('dynamicInput')">
I am hoping to create a dynamically created select with the details I added in the fields.
What I would like to happen is that I can loop through the values and create the options with the values that have been entered in the fields. My Javascript for this is below:
function addInput(divName) {
//other case here
case 'dropdown':
myInputs[counter]['atts'] = [];
myInputs[counter]['atts']['label'] = document.getElementById('fieldDropDownLabel').value
myInputs[counter]['atts']['one'] = document.getElementsByName('newDrop[]')
break;
}
var dd = document.createElement('select');
//other cases go here
case 'dropdown':
var label = document.createElement('label');
label.textContent = myInputs[counter]['atts']['label'];
label.setAttribute('for', myInputs[counter]['atts']['label']);
label.setAttribute('id', 'dropdown');
f.appendChild(label);
dd.setAttribute('name', myInputs[counter]['atts']['label'])
//default option
var option = document.createElement('option');
option.text = 'Please Select';
option.value = '';
dd.add(option, dd.options[null]);
//additional options
var option1 = document.createElement('option')
var newDrop = myInputs[counter]['atts']['one']
for(i=0; i < newDrop.length; i++)
{
option1.text = myInputs[counter]['atts']['one'];
option1.value = myInputs[counter]['atts']['one'];
dd.add(option1, dd.options[null]);
}
counter++;
f.appendChild(dd);
break;
I am just unable to get the values to show in the select options. Hopefully this is better than the last post.. Is there any chance someone can help?
Thanks

JavaScript- Changing input label color?

I would like to change the color of my input label through JavaScript. I'm doing the same with list items and selecting the input. They both work fine. However, it won't change the color of the label when I have it written the same way. Is my code incorrect? or is there another way to complete this task in a similar fashion?
My code:
//Highlights current page from submenu- This works
link = document.getElementById("<?php echo "$link";?>");
link.style.background = "#CCCCCC";
link.style.color = "#3385D6";
link.style.fontWeight = "bold";
link.style.border = "1px solid";
link.style.borderColor = "#BBBBBB";
//Highlights current submenu tab
subbtn = document.getElementById("<?php echo "$subTab";?>");
subbtn.checked= true;
//Doesn't work
subbtn.style.background = "#CCCCCC";
subbtn.style.color = "#3385D6";
subbtn.style.fontWeight = "bold";
My HTML:
<input type="radio" id="reveal-email">
<li><label for="reveal-email" >Tab that i want to change</label></li>
Based on your using a checked property on it, I'm going to guess that subbtn is an input type="checkbox" or input type="radio". So you're not setting the color and background of the label at all, that's a separate element.
If your HTML has the input inside the label (as is frequently the case), then:
var parentStyle = subbtn.parentNode.style;
parentStyle.background = "#CCCCCC";
parentStyle.color = "#3385D6";
parentStyle.fontWeight = "bold";
Live Example:
var subbtn = document.getElementById("subbtn");
var parentStyle = subbtn.parentNode.style;
parentStyle.background = "#CCCCCC";
parentStyle.color = "#3385D6";
parentStyle.fontWeight = "bold";
<label>
<input type="checkbox" id="subbtn"> This is the label
</label>
(The HTML you added indicates that you're using for instead, so see below.)
If your HTML has them separated and linked by the for attribute on the label matching the id of the checkbox, then the first line changes somewhat:
var parentStyle = document.querySelector('label[for="' + subbtn.id + '"]').style;
Live Example:
var subbtn = document.getElementById("subbtn");
var parentStyle = document.querySelector('label[for="' + subbtn.id + '"]').style;
parentStyle.background = "#CCCCCC";
parentStyle.color = "#3385D6";
parentStyle.fontWeight = "bold";
<input type="checkbox" id="subbtn">
<label for="subbtn">This is the label</label>
If you're not linking them in either way, you should, so that clicking the label will toggle the checkbox.

How to disable a text-box when clicking on other radio-buttons using a single function in javaScript?

I want to disable the text-box (its id is text1), when clicking on other radio buttons using a single function. According to my code the text-box is showing when the user is clicking on the radio button (its id is rd_other). But when the user clicking on the other radio buttons, after clicking the above radio button (its id is rd_other) the text-box is not disabling.
Here is HTML my code.
<input type="radio" name="rd_other" id="rd_other" value="rd_other" data-toggle="radio" onchange="enableText()">Other (please specify)
<input type="text" name="text1" id="text1"class="form-control input-sm jfl" readonly="readonly" style="display: none;"/>
<input type="radio" name="rdn1" id="rdn1" value="rdn1" data-toggle="radio">I haven't received the disc
<input type="radio" name="rdn2" id="rdn2" value="rdn2" data-toggle="radio">I lost or damaged the protective cover
Here is my javaScript code.
function enableText() {
var text1 = document.getElementById('text1');
text1.readOnly = false;
text1.style.display = 'block';
}
Firstly, to make sure there are no confusions, onchange will only fire when a radio button is selected.
Secondly, you would have to hook up an onchange function to the two other radio buttons. The function below should work.
function disableText() {
var text1 = document.getElementById('text1');
text1.readOnly = true;
text1.style.display = 'none';
}
like this
function disable() {
//one radio button
var radio = document.getElementById("your_radio_button_id");
var checkbox = document.getElementById("your_checkbox_id");
if (radio.checked == true) {
checkbox.disabled = true;
}
}
or like this
function disable() {
var radios = document.getElementsByName("your_radio_button_group_name");
var checkbox = document.getElementById("your_checkbox_id");
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked == true) {
checkbox.disabled = true;
}
}
}
You can fix this like this:
window.enableText = function(e) {
var text1 = document.getElementById('text1');
if(e.id == "rd_other2") {
text1.readOnly = false;
text1.style.display = 'block';
}
else{
text1.readOnly = true;
text1.style.display = 'none';
}
}
please check the full example here :)

Adding a button on clicking a radio button having same value as of the radio button

I am new to Javascript and HTML.
I am working on a project which have a lot of radio buttons.
<input type="radio" name="name" value="Run $temp" data-href="test.pl" onclick="function()"/>Text
I want to display a button with the value same as of the radio button(which is "Run $temp" in this case) after this "Text", whenever I click on the radio button.
How should I write function().
Thanks
UPDATED
<input type="radio" name="name" id="button1" value="Run $temp" data-href="test.pl" onclick="doStuff('id')"/>Text
JS
<script>
var prevButton;
function doStuff(id) {
if(prevButton){
prevButton.parentNode.removeChild(prevButton);
}
var radio= document.getElementById(id);
var button = document.createElement('button');
button.innerHTML = radio.value;
radio.parentNode.insertBefore(button, radio.nextSibling.nextSibling);
prevButton = button;
}
try doing this on click.
UPDATED
You have to keep reference of previous button added, to remove it when the next radio button is clicked.
Pass the name of the radio button you want to bind this function with.
<input type="radio" id="thisId" value="Run $temp" data-href="test.pl" onclick="doStuff('thisId');"/>Text
<script>
var prevButton;
function doStuff(id) {
if(prevButton){
prevButton.parentNode.removeChild(prevButton);
}
var radio= document.getElementById(id);
var button = document.createElement('BUTTON');
button.innerHTML = radio.value;
radio.parentNode.insertBefore(button, radio.nextSibling.nextSibling);
prevButton = button;
}
</script>
EDIT:
document.getElementById(id) returns one element and not an array, so there's no need for [0] to select the first element. Either that's the mistake you were making Or, its that you typed ID in all caps, document.getElementBy*Id*(id). Id has smaller d.
here's the fiddle.
I don't know if I understand you want to do, but try this:
<script type="text/javascript">
function setText() {
var textValue = document.getElementById("new_value");
textValue.innerHTML = "Text";
}
</script>
<input type="radio" name="name" value="Run $temp" data-href="test.pl" onclick="setText()"/><span id="new_value"></span>
Will this get you started?
function createBtn() {
var radioBtn = document.getElementById("run-temp-btn"),
radioBtnText = radioBtn.value,
btn = document.createElement("button"),
t = document.createTextNode(radioBtnText),
row1 = document.getElementById("row-1");
btn.appendChild(t);
row1.appendChild(btn);
}

Categories