JavaScript: Remove HTML form input group - javascript

I'm having some issues getting the removeElement function to work as expected. I want the addElement function to add a new input group with a dropdown and a Remove button (which it does). The Remove button should call the removeElement function, removing the respective input group, which it does the first time but no more.
Here is the Code:
function addElement(parentId, elementTag, elementId, html) {
// Adds an element to the document
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
var serviceID = 0; // reset number of services added
function addService() {
serviceID++; // increment for UID for new input
var html = `<div class="form-row"><div class="form-group col-6"><select name="service[]" class="form-control"><option value="basic">Basic Service</option><option value="full">Full Service</option><option value="tie">Ski Tie</option></select></div><div class="form-group col-3"><input type="button" class="btn btn-danger" onclick="javascript:removeElement('service' + serviceID + ''); return false;" value="Remove"></div></div>`;
addElement('services', 'div', 'service' + serviceID, html);
}
<div id="services">
<h4>Services</h4><br>
<div class="form-row">
<div class="form-group col-6">
<select name="service[]" class="form-control">
<option value="basic">Basic Service</option>
<option value="full">Full Service</option>
<option value="tie">Ski Tie</option>
</select>
</div>
</div><br>

There seems to be two issues in your code (based on what you have shared)
serviceID needs to be declared globally so that onclick handler can access the same.
No element is assigned the id as services
like
<h4 id="services">Services</h4><br>
Finally you need to invoke addService method as well.
Demo
var serviceID = 0;
function addElement(parentId, elementTag, elementId, html) {
// Adds an element to the document
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
function addService() {
serviceID++; // increment for UID for new input
var html = `<div class="form-row"><div class="form-group col-6"><select name="service[]" class="form-control"><option value="basic">Basic Service</option><option value="full">Full Service</option><option value="tie">Ski Tie</option></select></div><div class="form-group col-3"><input type="button" class="btn btn-danger" onclick="javascript:removeElement('service' + serviceID + ''); return false;" value="Remove"></div></div>`;
addElement('services', 'div', 'service' + serviceID, html);
}
addService() ;
<h4 id="services">Services</h4><br>
<div class="form-row">
<div class="form-group col-6">
<select name="service[]" class="form-control">
<option value="basic">Basic Service</option>
<option value="full">Full Service</option>
<option value="tie">Ski Tie</option>
</select>
</div>
</div>

Related

how to fix adding input not being double when selecting?

I'm stuck append double, I know the problem is that when I select the first I choose dynamic, when I change the second it selects static when I add the option button, why does the input become double?. how to fix append input not double. but if I first choose static and don't choose anything else, then not problem.
$(document).on('change', '#select-input-view', function(e) {
e.preventDefault()
let select = $(this).find(':selected').attr('data-input')
arr_select = select.split("-")
if (arr_select[1] == 'static') {
document.getElementById('select-id-input-view-' + arr_select[2]).innerHTML = ``
document.getElementById('select-id-input-view-' + arr_select[2]).innerHTML = `
<div id="static-option-${arr_select[2]}" class="mb-3">
<button id="add-option-select-view-${arr_select[2]}" class="btn btn-primary">add option</button>
<button id="remove-option-select-view-${arr_select[2]}" class="btn btn-danger">remove option</button>
<div id="view-option-${arr_select[2]}" class="mt-3">
</div>
</div>
`
var num_option_insert = $('.data-div-option').length;
$(document).on('click', '#add-option-select-view-' + arr_select[2], function(e) {
e.preventDefault()
thisid = this.id
arr_id = thisid.split("-")
num_option_insert += 1
option = `
<div id="option-div-view-${num_option_insert}-${arr_id[4]}" data-div-option="${num_option_insert}" class="col-md-3">
<label class="form-label">select option ${num_option_insert}</label>
<input name="123" type="text" class="form-control" required>
</div>
`
view_option = document.getElementById('view-option-' + arr_id[4])
$(view_option).append(option)
})
// delete fields
$(document).on('click', '#remove-option-select-view-' + arr_select[2], function(e) {
e.preventDefault()
thisid = this.id
arr_id = thisid.split("-")
console.log(arr_id)
var row = $('#option-div-view-' + num_option_insert + '-' + arr_id[4]);
row.remove();
num_option_insert -= 1
})
} else {
document.getElementById('select-id-input-view-' + arr_select[2]).innerHTML = ``
document.getElementById('select-id-input-view-' + arr_select[2]).innerHTML = `
<div id="dynamic-option-1" class="mb-3">
<div class="mb-3">
<label class="form-label">Select Data Dynamic</label>
<select name="select-dynamic" class="form-select" required>
<option selected disabled>Select data dynamic</option>
<?php foreach ($table_database as $data) {
$table = $data->Tables_in_db_builder;
$arr = explode("_", $table);
if ($arr[0] != 'sys') {
?>
<option><?= $data->Tables_in_db_builder ?></option>
<?php }
} ?>
</select>
</div>
</div>`
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select-input-view" name="input-type" class="form-select">
<option>text</option>
<option>number</option>
<option>textarea</option>
<option data-input="select-static-1">select static</option>
<option data-input="select-dynamic-1">select dynamic</option>
<option>float</option>
<option>date</option>
</select>
<div id="select-id-input-view-1">
</div>
Use event delegation so you only create listeners for the add-option and remove-option buttons once, not every time you add a new set of buttons.
Also, this line was wrong:
var num_option_insert = $('.data-div-option').length;
You have no data-div-option class, you have attributes like data-div-option="${num_option_insert}". The correct selector to match these elements is [data-div-option].
$(document).on('click', '.add-option-select-view', function(e) {
e.preventDefault()
var num_option_insert = $('[data-div-option]').length;
thisid = this.id
arr_id = thisid.split("-")
num_option_insert += 1
option = `
<div id="option-div-view-${num_option_insert}-${arr_id[4]}" data-div-option="${num_option_insert}" class="col-md-3">
<label class="form-label">select option ${num_option_insert}</label>
<input name="123" type="text" class="form-control" required>
</div>
`
view_option = document.getElementById('view-option-' + arr_id[4])
$(view_option).append(option)
})
// delete fields
$(document).on('click', '.remove-option-select-view', function(e) {
e.preventDefault()
var num_option_insert = $('[data-div-option]').length;
thisid = this.id
arr_id = thisid.split("-")
console.log(arr_id)
var row = $('#option-div-view-' + num_option_insert + '-' + arr_id[4]);
row.remove();
num_option_insert -= 1
})
$(document).on('change', '#select-input-view', function(e) {
e.preventDefault()
let select = $(this).find(':selected').attr('data-input')
arr_select = select.split("-")
if (arr_select[1] == 'static') {
document.getElementById('select-id-input-view-' + arr_select[2]).innerHTML = `
<div id="static-option-${arr_select[2]}" class="mb-3">
<button id="add-option-select-view-${arr_select[2]}" class="btn btn-primary add-option-select-view">add option</button>
<button id="remove-option-select-view-${arr_select[2]}" class="btn btn-danger remove-option-select-view">remove option</button>
<div id="view-option-${arr_select[2]}" class="mt-3">
</div>
</div>
`
} else {
document.getElementById('select-id-input-view-' + arr_select[2]).innerHTML = `
<div id="dynamic-option-1" class="mb-3">
<div class="mb-3">
<label class="form-label">Select Data Dynamic</label>
<select name="select-dynamic" class="form-select" required>
<option selected disabled>Select data dynamic</option>
<?php foreach ($table_database as $data) {
$table = $data->Tables_in_db_builder;
$arr = explode("_", $table);
if ($arr[0] != 'sys') {
?>
<option><?= $data->Tables_in_db_builder ?></option>
<?php }
} ?>
</select>
</div>
</div>`
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select-input-view" name="input-type" class="form-select">
<option>text</option>
<option>number</option>
<option>textarea</option>
<option data-input="select-static-1">select static</option>
<option data-input="select-dynamic-1">select dynamic</option>
<option>float</option>
<option>date</option>
</select>
<div id="select-id-input-view-1">
</div>

Run javascript code after template load and populate data from Google Sheet

I’m trying to create a web app, using Google Apps Script, in which when the the the certain condition are met, it will enable the Select Element with id="posAppDesired" then it will run the Google Apps Script to get the array of options, then return the array to the JavaScript and change the innerHTML of the Select Element. Then if the button with the id="addPositionId" is clicked, it will add a template and then it should load or duplicate the same option.
Here is the HTML code:
<!-- POSITION APPLIED FOR-->
<div class="form-row">
<div class="form-group col-sm-9">
<label for="posAppDesired">Select Desired Position</label>
<div class="input-group">
<select class="custom-select" id="posAppDesired" disabled>
<option selecte disabled>Choose...</option>
</select>
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="addPositionId"disabled>Add</button>
</div>
</div>
</div>
</div>
<!-- FOR TEMPLATE -->
<div class="form-row" id="desiredPosition"></div>
<!-- MY TEMPLATE -->
<template id="positionApplied">
<div class="form-group col-sm-9 posLine">
<div class="input-group">
<select class="custom-select templatePositionClass" id="templatePosition" aria-label="Example select with button addon">
<option selected>Choose...</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<div class="input-group-append">
<button class="btn btn-outline-secondary addPosButton" type="button">Add</button>
<button class="btn btn-outline-secondary removePosButton" type="button">Remove</button>
</div>
</div>
</div>
</template>
My JavaScript code:
<script>
var arrayOfPositions;
var currentlyAddedPositions = [];
document.getElementById("addPositionId").addEventListener("click", displayAddPosition);
document.getElementById("desiredPosition").addEventListener("click", afterDesiredPositionClicked);
function conditionOKAY(){
var rollNum = document.getElementById("rnum").value;
var appCat = document.getElementById("posCat").value;
document.getElementById("posAppDesired").disabled = false;
document.getElementById("addPositionId").disabled = false;
google.script.run.withSuccessHandler(positionCategoryCheck).getPositionCategory(IDNum, appCat);
}
function positionCategoryCheck(returnedPositions){
arrayOfPositions = returnedPositions.filter(function(r){ return true; });
var positionApplying = document.getElementById("posAppDesired");
uniquePositions(positionApplying, arrayOfPositions, 0);
}
function uniquePositions(el, arrayOfPositions, index){
// var currentlyAddedPositions = [];
el.innerHTML = '<option selected disabled style="font-color: #B0B0B0;" value=""> Select Desired Station</option>';
arrayOfPositions.forEach(function(r){
if(currentlyAddedPositions.indexOf(r[index]) === -1){
var option = document.createElement("option");
option.textContent = r[index];
el.appendChild(option);
currentlyAddedPositions.push(r[index]);
}
});
}
//------FOR DESIRED POSITION/S----////
function displayAddPosition(arrayOfPositions){
var addPosition = document.getElementById("desiredPosition");
var positionTemplate = document.getElementById("positionApplied");
var copyTemplate = positionTemplate.content.cloneNode(true);
addPosition.appendChild(copyTemplate);
var testPost = document.querySelector(".templatePositionClass").closest(".posLine");
var copiedPost = [];
testPost.innerHTML = '<option selected disabled style="font-color: #B0B0B0;" value=""> Select Desired Station</option>';
currentlyAddedPositions.forEach(function(r){
if(copiedPost.indexOf(r) === -1){
var option = document.createElement("option");
option.textContent = r;
testPost.appendChild(option);
copiedPost.push(r[0]);
}
});
}
function removePosition(){
document.getElementById("desiredPosition")
}
function afterDesiredPositionClicked(e){
if (e.target.matches(".addPosButton *, .addPosButton")){
displayAddPosition();
} else if (e.target.matches(".removePosButton *, .removePosButton")){
e.target.closest(".posLine").remove();
}
}
</script>
My Google Apps Script code:
function getPositionCategory(IDNum, appCat){
if(appCat == "Main"){
const ss = SpreadsheetApp.openByUrl(urlPrequalData);
const ws = ss.getSheetByName("VacantPositions");
const posSelection = ws.getRange(1,1,1, ws.getLastColumn()).getValues()[0];
var index = posSelection.indexOf(appCat)+1;
var posValues = ws.getRange(2, index, ws.getLastRow()-1, 1).getValues();
return posValues;
}
The JavaScript code above was able to add the template, and then change the innerHTML of the option element of that template. But if I click the add button again, the option element of the additional template does not change.
My aim is every time I clicked the "Add" button, it will load the template and right after the template loads, change the option in the Select Element of that template.

generate dynamic div and retrieve value of input elements

I am having div with input elements with Add and Cancel buttons.
When user clicked on add Button,I need to generate div with the same input elements and capture the value to JSon object.
Here is my code snippet
<div id="filterfields" class="row collapse">
<form class="form-inline" id="filterFieldsForm">
<select class="form-control" name="TypeCode" id="filterType_0">
<option value="Type">Type</option>
<option value="SubmittedBy">SubmittedBy</option>
<option value="Date">Date</option>
<option value="Description">Description</option>
</select>
<select class="form-control" name="Filter" id="filterCondition_0">
<option value="Equal">Equal</option>
<option value="StartsWith">Starts With</option>
<option value="EndsWith">Ends With</option>
<option value="Greaterthan">Greater Than</option>
<option value="Lessthan">Less Than</option>
</select>
<input type="text" name="caseFilterText" class="form-control" id="filterText_0">
<input class="form-control" type="radio" name="inlineRadioOptions" id="andRadio_0" value="AND">
<label for="andRadio">AND</label>
<input class="form-control" type="radio" name="inlineRadioOptions" id="orRadio_0" value="OR">
<label for="orRadio">OR</label>
<button id="addBtn_0" type="button" class="btn btn-secondary">Add</button>
<button id="cancelBtn_0" type="button" class="btn btn-secondary">Cancel</button>
</form>
</div>
I tried with clone and trying to retrieve values from the input elements inside div,but I am facing issue with getting values and generating ids.
$('#addBtn_' + count).click(function () {
var newel = $("#filterfields").clone(true);
var jsonData = [];
$(newel).insertAfter("#filterfields");
var index;
$("#filterfields").find('input:text,select').each(function () {
let str = '{"' + this.id + '":' + (this.value + '}';
jsonData.push(str);
}).end()
newel.find(':input').each(function () {
var oldId = $(this).attr("id");
var split = oldId.toString().split('_');
index = parseInt(split[1]);
var curId = split[0];
var newId = curId + "_" + index + 1;
this.id = newId;
}).end()
jsonData.push('"filterClause":' + $('input[name="inlineRadioOptions"]:checked').val() + '"');
});
Please suggest me if there is better way to achieve the similar function as I am not able to get values of input elements of current row.
Consider the following code.
$(function() {
function formToJson(fObj) {
var j = [];
fObj.children().not("button, label").each(function(i, el) {
// Will avoid buttons and labels
if (!($(el).is(":radio") && !$(el).is(":checked"))) {
// Will avoid unselected Radio Buttons
var d = {
nodeName: $(el).prop("nodeName"),
props: {
class: $(el).attr("class"),
id: $(el).attr("id")
},
value: $(el).val(),
name: $(el).attr("name")
};
if (d.nodeName != "SELECT") {
d.props.type = $(el).attr("type");
}
j.push(d);
}
});
return j;
}
$("[id^='addBtn']").click(function() {
var jsonData = formToJson($("#filterFieldsForm"));
console.log(jsonData);
var filter = "Filter: ";
$.each(jsonData, function(key, item) {
if (key != 2) {
filter += item.value + " ";
} else {
filter += "'" + item.value + "' ";
}
});
$("<div>", {
class: "filter-results"
}).html(filter).appendTo("body");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="filterfields" class="row collapse">
<form class="form-inline" id="filterFieldsForm">
<select class="form-control" name="TypeCode" id="filterType_0">
<option value="Type">Type</option>
<option value="SubmittedBy">SubmittedBy</option>
<option value="Date">Date</option>
<option value="Description">Description</option>
</select>
<select class="form-control" name="Filter" id="filterCondition_0">
<option value="Equal">Equal</option>
<option value="StartsWith">Starts With</option>
<option value="EndsWith">Ends With</option>
<option value="Greaterthan">Greater Than</option>
<option value="Lessthan">Less Than</option>
</select>
<input type="text" name="caseFilterText" class="form-control" id="filterText_0">
<input class="form-control" type="radio" name="inlineRadioOptions" id="andRadio_0" value="AND">
<label for="andRadio">AND</label>
<input class="form-control" type="radio" name="inlineRadioOptions" id="orRadio_0" value="OR">
<label for="orRadio">OR</label>
<button id="addBtn_0" type="button" class="btn btn-secondary">Add</button>
<button id="cancelBtn_0" type="button" class="btn btn-secondary">Cancel</button>
</form>
</div>
As you are iterating over elements, it is best to use .each(). Using the proper selector, we can target just the form elements you want. You then want a condition to ensure that if a Radio Button is selected (or checked) that it is included and others are excluded.
The result is an Array of Objects that can be used to rebuild the HTML Structure or just build new copies.
Update
$(function() {
function formToJson(fObj) {
var j = [];
fObj.each(function(i, el) {
var d = {};
$("select, input", el).each(function(k, v) {
if (!($(v).is(":radio") && !$(v).is(":checked"))) {
d[$(v).attr("id")] = $(v).val();
}
});
j.push(d);
});
return j;
}
$("[id^='addBtn']").click(function() {
var jsonData = formToJson($("#filterFieldsForm"));
console.log(jsonData);
var filter = "Filter: ";
$.each(jsonData, function(key, item) {
if (key != 2) {
filter += item.value + " ";
} else {
filter += "'" + item.value + "' ";
}
});
$("<div>", {
class: "filter-results"
}).html(filter).appendTo("body");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="filterfields" class="row collapse">
<form class="form-inline" id="filterFieldsForm">
<select class="form-control" name="TypeCode" id="filterType_0">
<option value="Type">Type</option>
<option value="SubmittedBy">SubmittedBy</option>
<option value="Date">Date</option>
<option value="Description">Description</option>
</select>
<select class="form-control" name="Filter" id="filterCondition_0">
<option value="Equal">Equal</option>
<option value="StartsWith">Starts With</option>
<option value="EndsWith">Ends With</option>
<option value="Greaterthan">Greater Than</option>
<option value="Lessthan">Less Than</option>
</select>
<input type="text" name="caseFilterText" class="form-control" id="filterText_0">
<input class="form-control" type="radio" name="inlineRadioOptions" id="andRadio_0" value="AND">
<label for="andRadio">AND</label>
<input class="form-control" type="radio" name="inlineRadioOptions" id="orRadio_0" value="OR">
<label for="orRadio">OR</label>
<button id="addBtn_0" type="button" class="btn btn-secondary">Add</button>
<button id="cancelBtn_0" type="button" class="btn btn-secondary">Cancel</button>
</form>
</div>
This will target the various rows and for each row, it will gather all the Select and Inputs.

How to create comma separated list from multiple select elements Javascript

I have a form of dynamically created single option select elements. What I need to do is create a list of all of the selected indexes of these elements, separated by a comma. I'm using
elements = document.getElementsByClassName("my-class");
to grab a node list (whatever one of those is, I'm guessing like an array?) of all of the select elements, and I know about .selectedindex, but I'm stuck from there.
I would like to get an output like:
3,4,6,1
I want to use this data in a query string to do some magic.
Any help is appreciated.
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
var counterid = counter;
var newdivid = "dynamic-div-"+counterid;
newdiv.setAttribute("id", newdivid);
oldelement = document.getElementById('cat-drop-id');
newelement = oldelement.cloneNode(true);
newdiv.innerHTML = "<br><select name='cat' id='cat-dropdown-id" + counterid + "' class='som-changecat-category-dropdown'>" + newelement.innerHTML + "</select><input type='button' id='remove-button-id" + counterid + "' value='Remove DUMMY' onclick='removeDummy(this.id);' /><br><br>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
function removeDummy(elementtoremove) {
var elem = document.getElementById(elementtoremove);
elem.parentNode.parentNode.removeChild(elem.parentNode);
return false;
}
<form action="?page=test-options-page&something=0" method="POST">
<div id="dynamicInput">
<select name="cat" id="cat-drop-id" class="som-changecat-category-dropdown">
<option value="-1">Select category</option>
<option class="level-0" value="1">test</option>
<option class="level-0" value="2">test2</option>
</select>
</div>
<input type="button" value="Add another dropdown" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit">
</form>
you just need to convert nodeList to array.
and you can get more info about it here: https://davidwalsh.name/nodelist-array
below is the full working code.
notice the extra button i add and getValue() method =)
<form action="?page=test-options-page&something=0" method="POST">
<div id="dynamicInput">
<select name="cat" id="cat-drop-id" class="som-changecat-category-dropdown">
<option value="-1">Select category</option>
<option class="level-0" value="1">test</option>
<option class="level-0" value="2">test2</option>
</select>
</div>
<input type="button" value="Add another dropdown" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit">
<button onClick="getValue(event)">get comma seperated value</button>
</form>
<script>
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
var counterid = counter;
var newdivid = "dynamic-div-"+counterid;
newdiv.setAttribute("id", newdivid);
oldelement = document.getElementById('cat-drop-id');
newelement = oldelement.cloneNode(true);
newdiv.innerHTML = "<br><select name='cat' id='cat-dropdown-id" + counterid + "' class='som-changecat-category-dropdown'>" + newelement.innerHTML + "</select><input type='button' id='remove-button-id" + counterid + "' value='Remove DUMMY' onclick='removeDummy(this.id);' /><br><br>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
function removeDummy(elementtoremove) {
var elem = document.getElementById(elementtoremove);
elem.parentNode.parentNode.removeChild(elem.parentNode);
return false;
}
function getValue(event) {
event.preventDefault();
// all select element.
var selects = document.getElementById('dynamicInput').querySelectorAll('select');
// convert nodeList to array
var selectsArray = Array.prototype.slice.call(selects)
// now you can use Array.prototype.*
var result = selectsArray.map(select => {
return select.value;
}).join(',');
// do what ever you want with `result` now.
console.log(result);
return result;
}
</script>
As .selectedOptions is still isn’t safe to go with there is nothing more than to iterate the options of each select and get the selected ones. Try something like:
var selects = document.getElementsByClassName('som-changecat-category-dropdown');
var values = {}, select, id, optionValues;
for (var i = 0; i < selects.length; i++) {
select = selects[i];
id = select.id;
optionValues = [];
for (var j = 0; j < select.options.length; j++) {
var option = select.options[j];
if (option.selected) optionValues.push(option.value);
}
values[select.id] = optionValues.join(',');
}
// gives you an object with the selects’ ids as keys
//and the komma separated values as value
document.write(JSON.stringify(values));
<form action="?page=test-options-page&something=0" method="POST">
<div id="dynamicInput">
<select multiple id="cat-dropdown-1" class="som-changecat-category-dropdown">
<option value="1" selected>bli</option>
<option value="2">bla</option>
<option value="3" selected>blu</option>
</select>
<select multiple id="cat-dropdown-2" class="som-changecat-category-dropdown">
<option value="4">blimm</option>
<option value="5" selected>blamm</option>
<option value="6" selected>blumm</option>
</select>
</div>
<input type="button" value="Add another dropdown" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit">
</form>
You could make this work to collect all the form elements’ values and use the resulting object as a base for creating your query string.

javascript getElementById start with

I want to select div start with * to change it from display: block to display:hidden
function select_to_text(a) {
var as = '#' + a;
var aa = $(as).val();
if (aa == "0") {} else {
//var $eles = $(":*[name^='personal_family_type_']").css("background-color","yellow");
document.getElementById(a + "_" + aa + "_block").style.display = 'block';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="personal_family_type" class="control-label col-sm-2">type</label>
<div class="col-sm-10">
<select size="1" id="personal_family_type" name="personal_family_type" class="form-control btn btn-primary" onchange="select_to_text('personal_family_type')">
<option value="0">----</option>
<option value="wife">Wife</option>
<option value="husband">Husband</option>
<option value="son">Son</option>
<option value="all">Show all</option>
</select>
<div id="personal_family_type_wife_block" style="display :none">
wife
</div>
<div id="personal_family_type_husband_block" style="display :none">
husband
</div>
<div id="personal_family_type_son_block" style="display :none">
son
</div>
</div>
</div>
you should not pass in params to your onchange handler -- you can get more flexibility if you tap into the event callback stuff via javascript. I'd also utilize classes to find your elements of interest...there are ways to make the selector more efficient, but to illustrate the point, I'm keeping it simple.
to start -- replace some of the encoded information from the id of the divs with class names and remove the onchange property.
<div class="form-group">
<label for="personal_family_type" class="control-label col-sm-2">type</label>
<div class="col-sm-10">
<select size="1" id="personal_family_type" name="personal_family_type" class="form-control btn btn-primary" >
<option value="0">----</option>
<option value="wife">Wife</option>
<option value="husband">Husband</option>
<option value="son">Son</option>
<option value="all">Show all</option>
</select>
<div id="wife_block" class="personal_family_type" style="display :none">
wife
</div>
<div id="husband_block" class="personal_family_type" style="display :none">
husband
</div>
<div id="son_block" class="personal_family_type" style="display :none">
son
</div>
</div>
</div>
next, bind your select element to the onchange handler and then the logic in select_to_text, in a nutshell:
set all elements to display:none, then set the specific elements to display:block per the settings (I'm assuming I understand the way this is supposed to work).
script:
$('#personal_family_type').on('change',select_to_text);
function select_to_text(evt) {
var $blocks;
$blocks = $('.'+evt.target.id).hide();
switch (evt.target.value) {
case '0':
break;
case 'all':
$blocks.show();
break;
default:
$('#' + evt.target.value + "_block").show();
}
}
Here is a solution done in jQuery. Remove the onclick from your html element.
$( document ).ready(function() {
$('#personal_family_type').on('click', function() {
$("#"+this.id + "_" + this.value + "_block").toggle();
});
});
Here is a Demo
You should definitely use jQuery in this case. If I understand your question correctly, you could do something like this:
$("#personal_family_type option:selected").click(function() {
var family_select_option = $(this).val();
$('#personal_family_type_'+family_select_option+'block').show();
});
Given:
<select size="1" id="personal_family_type" name="personal_family_type"
class="form-control btn btn-primary"
onchange="select_to_text('personal_family_type')">
You can instead do:
<select size="1" name="personal_family_type"
class="form-control btn btn-primary"
onchange="select_to_text(this)">
then in the function:
// a is a reference to the element calling the function
function select_to_text(a) {
var aa = a.value;
then I think you want:
if (aa !== "0") {
var el = document.getElementById(a.name + '_' + aa + '_block');
// set display to empty string so adopts default or inherited style
if (el) el.style.display = '';
}
}
which can be reduced to:
function select_to_text(a) {
if (aa.value !== '0')
document.getElementById(a.name + '_' + aa.value + '_block'.style.display = '';
}

Categories

Resources