How to get the input value of a checkbox (true/false) - javascript

I have this html and I am trying to get the input value of a certain checkbox
var option = document.createElement('li');
var checkbox = document.createElement('input');
var label = document.createElement('label')
var optionId = "option" + "" + questionNumber + subquestionNumber;
var checkBoxId = "checkbox" + "" + questionNumber + subquestionNumber;
var labelId = "label" + "" + questionNumber + subquestionNumber;
var labelname = "name" + "" + questionNumber + subquestionNumber;
checkbox.type = "checkbox";
label.id = labelId;
label.name= labelname;
option.id = optionId;
option.className = "optionName";
checkbox.id = checkBoxId;
checkBoxId.htmlFor = option;
label.appendChild(document.createTextNode('Option ' + subquestionNumber));
option.appendChild(label); //add `label` to `li`
option.appendChild(checkbox); //add `checkbox` to `li`
q.appendChild(option);
var checkboxes = document.querySelector(labelId);
document.getElementById("testingBox6").innerHTML = checkboxes;
I want to save the input value to the variable checkboxes
Thank you for your time

With Jquery, it can be simple. But, you can try this without Jquery
document.getElementById(checkboxId).checked;

you can get true/false with checked
for example
var checkbox = document.createElement('input');
checkbox.setAttribute("type", "checkbox");
checkbox.addEventListener("change", ()=> {
console.log(checkbox.checked); // it gives true or false when you clicked
})

Or even you can use
document.querySelector('#checkBoxId').checked;

Related

javascript - `<form>` and `</form>` in same line .Other elements generated outside form

I am creating a form using javascript ,and subsequently adding the elements.
This code runs onclick event of a button .
But the generated code contains the <form> and </form> code in single line and the elements generated after this line.
I have given inline style border to the form.
The form border covers only one line and the controls are generated outside the form.
How to bring all elements between the <form> and </form> ?
A portion of my code below.
var f_id = frm_main_id + "_set" + (set_no + 1);
var criterias_csv_id = frm_main_id + '_criteria_csv';
var criterias_csv = document.getElementById(criterias_csv_id).value
var criteria_array = criterias_csv.split("|");
var fldno = 0;
var i;
var fid = "activity" + act_no + "_time_" + (set_no + 1) + "time";
var x = document.getElementById("id_" + act_no + "_fieldset")
var f = document.createElement("form");
f.setAttribute('method', "post");
f.setAttribute('id', f_id);
f.setAttribute('action', "submit_criteria.php");
f.style.borderStyle = "solid";
x.appendChild(f);
//var table = document.getElementById("id_" + act_no + "_table");
var new_table = document.createElement("TABLE");
new_table.setAttribute('class', "class_open");
new_table.setAttribute('form', f_id);
new_table.style.borderStyle = "solid";
x.appendChild(new_table);
var new_row = document.createElement("TR");
new_table.appendChild(new_row);
var th = document.createElement("th");
new_row.appendChild(th);
th.innerHTML = "Observed Time" + (set_no + 1);
var th = document.createElement("th");
new_row.appendChild(th);
var s = document.createElement("input");
s.setAttribute('type', "datetime-local");
s.setAttribute('id', fid);
s.setAttribute('form', f_id);
s.setAttribute('required', true);
th.appendChild(s);
for (i = 0; i < criteria_array.length; i += 2) {
fldno++;
fid = "activity" + act_no + "_time_" + (set_no + 1) + "_criteria_" + fldno;
var new_row = document.createElement("TR");
new_table.appendChild(new_row);
if (i == 0) {}
var field_type = "";
var fldname = criteria_array[i];
field_type = criteria_array[i + 1];
field_type = field_type.trim();
switch (field_type) {
case "Numeric":
field_type = "number";
break;
case "TEXT":
field_type = "text";
break;
}
var new_row = document.createElement("TR");
new_table.appendChild(new_row);
new_col = document.createElement("td");
new_row.appendChild(new_col);
new_col1 = document.createElement("td");
new_row.appendChild(new_col1);
new_label = document.createElement("label");
new_label.setAttribute("for", fid);
new_label.innerHTML = fldno + ")" + fldname;
new_col.appendChild(new_label);
switch (field_type) {
case "number":
case "text":
var s = document.createElement("input");
s.setAttribute('type', field_type);
s.setAttribute('id', fid);
s.setAttribute('required', true);
s.setAttribute('form', f_id);
new_col1.appendChild(s);
break;
case "YN":
var s = document.createElement("SELECT");
s.setAttribute('id', fid);
s.setAttribute('form', f_id);
var option = document.createElement("option");
option.text = "";
option.value = "";
s.add(option);
var option = document.createElement("option");
option.text = "No";
option.value = "N";
s.add(option);
var option = document.createElement("option");
option.text = "Yes";
option.value = "Y";
s.add(option);
new_col1.appendChild(s);
break;
default:
break;
}
}
new_row = document.createElement("TR");
new_table.appendChild(new_row);
new_col = document.createElement("td");
new_row.appendChild(new_col);
s = document.createElement("input"); //input element, Submit button
s.setAttribute('type', "submit");
s.setAttribute('value', "Save");
s.setAttribute('form', f_id);
s.setAttribute('onclick', "x()");
//"clk_save(', $act_no, ',', $edit, ')">
new_col.append(s);
new_col = document.createElement("td");
new_row.appendChild(new_col);
new_col.append(s);
}
I currently set the form attribute of each element separately and it works fine. But the border around the form is only for the first line.
Any idea??
Thanks for suggestions.
I have posted the full code.
I did following correction and everything is fine
x.appendChild(new_table); replaced x. with f.

remove disabled property from a html object in jquery

I am adding html on my page on click of a button.So when i adding the html i want to remove all the disabled property from the html variable so that the new html don't have any disabled inputs :
Code:
var current_td = $(thisobj).closest('tr').html();
var next_td = $(thisobj).closest('tr').siblings('tr.add').html();
var added1 = '<tr class="class2">'+current_td+'</tr>';
var added2 = '<tr class="class1">'+next_td+'</tr>';
var main_html = added1 + added2;
main_html = main_html.replace("Add[+]" ,"Remove [-]");
$('#create_table').append("<tbody id=TBody"+Count+">"+main_html+"</tbody>");
masterCodeCount++;
return "TBody"+(Count-1);
From main_html variable i want to remove the disabled property of the inputs types.Because from where i am getting the html the inputs type are disabled
You can do
var current_td = $(thisobj).closest('tr').html();
var next_td = $(thisobj).closest('tr').siblings('tr.add').html();
var added1 = '<tr class="class2">' + current_td + '</tr>';
var added2 = '<tr class="class1">' + next_td + '</tr>';
var main_html = added1 + added2;
main_html = main_html.replace("Add[+]", "Remove [-]");
var $main = $(main_html);
//remove the disabled attribute
$main.find(':disabled').removeAttr('disabled');
$("<tbody id=TBody" + Count + "></tbody>").append($main).appendTo('#create_table');
masterCodeCount++;
return "TBody" + (Count - 1);

Javascript onchange not catching on drop box change

OK I am attempting to use onchange to capture the value from a dropbx but while I select the the value in the box it never seems to catch the onchange and I get an undefined value for the variable I try and capture the change with. I popped print statement into the onchange function call and it never seems to pick up the value switch. Any help is greatly appreciated
newWindow = window.open("", null, "height=400,width=800,status=yes,toolbar=no,menubar=no,location=no");
newWindow.document.title = "Crafting Window";
newWindow.document.body.style.background = "#00214D";
newWindow.document.body.style.color = "White";
// create a form and set properties
var form = document.createElement('form');
form.method = 'post';
// insert into the body of the new window
newWindow.document.body.appendChild(form);
// add text before the input
var cNumLab = document.createElement('cNumLab');
form.appendChild(document.createTextNode('Craft Number:'));
// add a text input
var cNum = document.createElement('input');
cNum.type = 'text';
cNum.name = 'input';
cNum.value = '';
form.appendChild(cNum);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var sDescL = document.createElement('sDescL');
form.appendChild(document.createTextNode('Short Desc:'));
// add a text input
var sDesc = document.createElement('input');
sDesc.type = 'text';
sDesc.name = 'sDesc';
sDesc.value = '';
sDesc.size = 50;
form.appendChild(sDesc);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var lDescL = document.createElement('lDesc');
form.appendChild(document.createTextNode('Long Desc:'));
// add a text input
var lDesc = document.createElement('input');
lDesc.type = 'text';
lDesc.name = 'lDesc';
lDesc.value = '';
lDesc.size = 80;
form.appendChild(lDesc);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eDescL = document.createElement('eDescL');
form.appendChild(document.createTextNode('Extended Desc:'));
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add a text input
var eDesc = document.createElement('textarea');
eDesc.type = 'text';
eDesc.name = 'eDesc';
eDesc.value = '';
form.appendChild(eDesc);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eTools = document.createElement('eTools');
form.appendChild(document.createTextNode('Tools:'));
// add a text input
var eTool = document.createElement('input');
eTool.type = 'text';
eTool.name = 'eTools';
eTool.value = '';
form.appendChild(eTool);
var tools = document.createElement('select');
tools.id = 'sTools';
tools.name = 'sTools';
form.appendChild(tools);
var cTool;
var e = document.getElementById("sTools");
var options = [
["Forge 33", "33"],
["Workbench 1391", "1391"],
["Oven 1753", "1753"],
["Mortar-Pestle 3277", "3277"],
["Chisel 3349", "3349"],
["Pottery Wheel 3420", "3420"],
["Kiln 3421", "3421"],
["Blowpipe3422", "3422"],
["Bookbinder 3467", "3467"],
["Palette 3483", "3483"]
];
for (var i = 0; i < options.length; i++) {
var opt = document.createElement('option');
opt.appendChild(document.createTextNode(options[i][0]));
opt.value = options[i][1];
tools.appendChild(opt);
}
tools.onchange = function () {
print("GOT HERE");
cTool = e.options[e.selectedIndex].value;
alert(cTool);
};
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eIngreds = document.createElement('eIngreds');
form.appendChild(document.createTextNode('Ingredients:'));
// add a text input
var eIngred = document.createElement('input');
eIngred.type = 'text';
eIngred.name = 'eIngred';
eIngred.value = '';
eIngred.size = 50;
form.appendChild(eIngred);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eSteps1 = document.createElement('eSteps1');
form.appendChild(document.createTextNode('Step 1:'));
// add a text input
var eStep1 = document.createElement('input');
eStep1.type = 'text';
eStep1.name = 'eStep1';
eStep1.value = '';
eStep1.size = 80;
form.appendChild(eStep1);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eSteps1 = document.createElement('eSteps2');
form.appendChild(document.createTextNode('Step 2:'));
// add a text input
var eStep2 = document.createElement('input');
eStep2.type = 'text';
eStep2.name = 'eStep2';
eStep2.value = '';
eStep2.size = 80;
form.appendChild(eStep2);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eSteps3 = document.createElement('eSteps3');
form.appendChild(document.createTextNode('Step 3:'));
// add a text input
var eStep3 = document.createElement('input');
eStep3.type = 'text';
eStep3.name = 'eStep3';
eStep3.value = '';
eStep3.size = 80;
form.appendChild(eStep3);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eSteps4 = document.createElement('eSteps4');
form.appendChild(document.createTextNode('Step 4:'));
// add a text input
var eStep4 = document.createElement('input');
eStep4.type = 'text';
eStep4.name = 'eStep4';
eStep4.value = '';
eStep4.size = 80;
form.appendChild(eStep4);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eSteps5 = document.createElement('eSteps5');
form.appendChild(document.createTextNode('Step 5:'));
// add a text input
var eStep5 = document.createElement('input');
eStep5.type = 'text';
eStep5.name = 'eStep5';
eStep5.value = '';
eStep5.size = 80;
form.appendChild(eStep5);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eSteps6 = document.createElement('eSteps6');
form.appendChild(document.createTextNode('Step 6:'));
// add a text input
var eStep6 = document.createElement('input');
eStep6.type = 'text';
eStep6.name = 'eStep6';
eStep6.value = '';
eStep6.size = 80;
form.appendChild(eStep6);
var cTool;
var e = document.getElementById("sTools");
tools.onchange = function () {
cTool = e.options[e.selectedIndex].value;
alert(cTool);
};
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
var eSubmit = document.createElement('button');
eSubmit.type = 'button';
//eSubmit.name = 'Submit Design';
eSubmit.innerHTML = 'Submit Design';
eSubmit.onclick = function () {
if (sDesc.value !== "") {
client.send_direct("craft edit " + cNum.value + " short_desc " + sDesc.value);
}
if (lDesc.value !== "") {
client.send_direct("craft edit " + cNum.value + " long_desc " + lDesc.value);
}
if (eDesc.value !== "") {
client.send_direct("craft edit " + cNum.value + " extended_desc " + eDesc.value);
}
if (eIngred.value !== "") {
client.send_direct("craft ingredients " + cNum.value + " " + eIngred.value);
}
if (eTool.value !== "") {
client.send_direct("craft tools " + cNum.value + " add " + eTool.value);
}
if (eStep1.value !== "") {
client.send_direct("craft steps " + cNum.value + " change 1 1 " + eStep1.value);
}
if (eStep2.value !== "") {
client.send_direct("craft steps " + cNum.value + " change 2 1 " + eStep2.value);
}
if (eStep3.value !== "") {
client.send_direct("craft steps " + cNum.value + " change 3 1 " + eStep3.value);
}
if (eStep4.value !== "") {
client.send_direct("craft steps " + cNum.value + " change 4 1 " + eStep4.value);
}
if (eStep5.value !== "") {
client.send_direct("craft steps " + cNum.value + " change 5 1 " + eStep5.value);
}
if (eStep6.value !== "") {
client.send_direct("craft steps " + cNum.value + " change 6 1 " + eStep6.value);
}
alert(cTool);
};
form.appendChild(eSubmit);

Dynamic adding input fields into columns

I had this block of code in javascript which does add dynamic input fields. Every thing works fine at this point. My question is how would I add more input fields within the table in other cell respectively with the village name input fields? When user Add Village 1/Remove Village 1, either of the action should add/remove aligning input field on column named:Type of participatory forest management, Year participatory management process started and Size of forest. The input fields increment of the columns mentioned above should reflect the increment of dynamic input field of village name column. Later I will use the dynamic input fields with Php on sending the values to database. Thanks for your time!
Below is script:
script code:
<script language="JavaScript" type="text/javascript">
function getById(e){return document.getElementById(e);}
function newElement(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function addForestName()
{
var tbl = getById('tblSample'); //note the single line generic functions written above
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// Column which has iteration count
var cell_no = row.insertCell(0);
var textNode = newTxt(iteration);
cell_no.appendChild(textNode);
// Column which has the forest name
var frstNameCell = row.insertCell(1);
var el_input = newElement('input'); //create forest name input
el_input.type = 'text';
el_input.name = 'forest_text_' + iteration;
el_input.id = 'forest_text_' + iteration;
el_input.size = 40;
frstNameCell.appendChild(el_input);
// Column which has the village name
var villageNameCell = row.insertCell(2);
var el_label = newElement('label');
el_label.for = 'village_text_' + iteration + '_1';
var el_labelValue = '1.';
textNode = newTxt(el_labelValue);
el_label.appendChild(textNode);
villageNameCell.appendChild(el_label);
el_input = newElement('input');
el_input.type = 'text';
el_input.name = 'village_text_' + iteration + '_1';
el_input.id = 'village_text_' + iteration + '_1';
el_input.size = 40;
villageNameCell.appendChild(el_input);
el_btn = newElement('input'); //create village name add button
el_btn.type = 'button';
el_btn.name = 'village_btn_' + iteration;
el_btn.id = 'village_btn_' + iteration;
el_btn.value = 'Add Village Forest ' + iteration;
el_btn.addEventListener('click',addMoreVillageNames, false);
villageNameCell.appendChild(el_btn);
el_btn = newElement('input'); //create village name remove button
el_btn.type = 'button';
el_btn.name = 'village_rembtn_' + iteration;
el_btn.id = 'village_rembtn_' + iteration;
el_btn.value = 'Remove Village Forest ' + iteration;
el_btn.addEventListener('click',removeVillageName, false);
villageNameCell.appendChild(el_btn);
var frstManagCell = row.insertCell(3); // create forest management input
el_input = newElement('input');
el_input.type = 'text';
el_input.name = 'frstManage_text_' + iteration + '_1';
el_input.id = 'frstManage_text_' + iteration + '_1';
el_input.size = 40;
frstManagCell.appendChild(el_input);
var yerPartCell = row.insertCell(4); // create year participatory input
el_input = newElement('input');
el_input.type = 'text';
el_input.name = 'yrPart_text_' + iteration + '_1';
el_input.id = 'yrPart_text_' + iteration + '_1';
el_input.size = 40;
yerPartCell.appendChild(el_input);
var frstSizeCell = row.insertCell(5); // create forest size input
el_input = newElement('input');
el_input.type = 'text';
el_input.name = 'frstSize_text_' + iteration + '_1';
el_input.id = 'frstSize_text_' + iteration + '_1';
el_input.size = 40;
frstSizeCell.appendChild(el_input);
}
function addMoreVillageNames(){
rowNumber = (this.id).substring((this.id.length)-1, this.id.length); //to get Row Number where one more input needs to be added.
var childElCount;
var parentCell = this.parentNode;
var inputCount = parentCell.getElementsByTagName('label').length; //to get the count of input fields present already
var newFieldNo = inputCount + 1; //input current count by 1 to dynamically set next number for the new field
//temporarily remove the add and remove buttons to insert the new field before it.we are doing this loop only twice because we know the last 2 input elements are always the two buttons
for (var i=0; i<2; i++){
childElCount = parentCell.getElementsByTagName('input').length; //get count of child input elements (including text boxes);
parentCell.removeChild(parentCell.getElementsByTagName('input')[childElCount-1]);
}
var lineBreak = newElement('br');
parentCell.appendChild(lineBreak); //add a line break after the first field
var el_label = newElement('label');
el_label.for = 'village_text_' + rowNumber + '_' + newFieldNo;
var el_labelValue = newFieldNo + '.';
var textNode = newTxt(el_labelValue);
el_label.appendChild(textNode);
parentCell.appendChild(el_label); //create and add label
var el_input = newElement('input');
el_input.type = 'text';
el_input.name = 'village_text_' + rowNumber + '_' + newFieldNo;
el_input.id = 'village_text_' + rowNumber + '_' + newFieldNo;
el_input.size = 40;
parentCell.appendChild(el_input); //create and add input field
var el_btn = newElement('input'); //add the village name add button again
el_btn.type = 'button';
el_btn.name = 'village_btn_' + rowNumber;
el_btn.id = 'village_btn_' + rowNumber;
el_btn.value = 'Add Village ' + rowNumber;
el_btn.addEventListener('click',addMoreVillageNames, false);
parentCell.appendChild(el_btn);
el_btn = newElement('input'); //create village name remove button
el_btn.type = 'button';
el_btn.name = 'village_rembtn_' + rowNumber;
el_btn.id = 'village_rembtn_' + rowNumber;
el_btn.value = 'Remove Village ' + rowNumber;
el_btn.addEventListener('click',removeVillageName, false);
parentCell.appendChild(el_btn);
}
function removeForestName()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
function removeVillageName()
{
var rowNumber = (this.id).substring((this.id.length)-1, this.id.length); //to get Row Number where one more input needs to be added.
var parentCell = this.parentNode;
var lblCount = parentCell.getElementsByTagName('label').length;
var inputCount = parentCell.getElementsByTagName('input').length;
var brCount = parentCell.getElementsByTagName('br').length;
//Remove will not happen if there is only one label-input combo left.
if(lblCount>1)
parentCell.removeChild(parentCell.getElementsByTagName('label')[lblCount-1]);
if(inputCount>3)
parentCell.removeChild(parentCell.getElementsByTagName('input')[inputCount-3]); //Delete the third last element because the last two are always the two buttons.
parentCell.removeChild(parentCell.getElementsByTagName('br')[brCount-1]);
}
window.onload = addForestName;
</script>
<form action="tableaddrow_nw.html" method="get">
<table width="640" border="1" id="tblSample">
<tr>
<td>No.</td>
<td>Forest Name</td>
<td width="40">Name of the villages <br />participating in managing</td>
<td>Type of participatory forest management</td>
<td>Year participatory management process started</td>
<td>Size of forest</td>
</tr>
</table>
</form>
<p>
<input type="button" value="Add" onclick="addForestName();" />
<input type="button" value="Remove" onclick="removeForestName();" />
</p>
If I understood your question correctly, the below is what you are looking for. Using the following method you can get hold of the required table column (Column Number is hard coded because this is just a sample). Once you have got hold of the required column, adding/removing fields should be straight-forward. Check out this Fiddle for a working sample.
var tbl = document.getElementById('tblSample');
var frstMgmtCell = tbl.rows[rowNumber].cells[3]; //Get hold of the Forest Mgmt Column of that specific row.
On a side note, there are a lot of repeated items which you might want to convert into separate functions for better maintainability.

Copying dropdown values

I'm trying to copy two dropdown values and add them to a textarea. I copy one just fine but can't copy two. I'm trying to copy the value of 'amount' and the value of 'type' combine them and insert into a textarea. My code:
function copy() {
var sel = document.getElementById("amount");
var text = sel.options[sel.selectedIndex].value;
var out = document.getElementById("textarea");
out.value += text + "\n";
}
var sel1 = document.getElementById("amount");
var sel2 = document.getElementByid("type");
var amt = sel1.options[sel1.selectedIndex].value;
var typ = sel2.options[sel2.selectedIndex].value;
var out = document.getElementById("textarea");
out.value += amt + " " + typ + "\n";
You may want to rename your field named "type" as that could very possibly be a reserved variable name.
Also, I don't see where you are pulling in the value of type? Try this:
function copy() {
var sel = document.getElementById("amount");
var textInput = document.getElementById("some_type");
var text = sel.options[sel.selectedIndex].value + textInput.value;
var out = document.getElementById("textarea");
out.value += text + "\n";
}

Categories