I am trying to show and hide certain div based on selected text in drop down list. The option in drop-down list is generated by getting id from certain class name. I thought of using looping of an array in javascript but am unsure how to do so. Sorry that i may sound unclear of what i wanted to do as i am lost and unsure how to do them.
My Codes:
JavaScript:
var elements = document.body.getElementsByClassName("headline-bar");
window.onload = function() {
var year = document.getElementById("year");
for (i=0;i<elements.length;i++)
{
var Entry = document.createElement("option");
Entry.text = elements[i].textContent;
year.add(Entry ,null);
}
}
Html:
<form>
<select id="year">
<option>All</option>
</select>
<input type="submit" value="Submit">
</form>
<form action="#" id="release_year" method="post" >
<div class="release_holder" id="2015" style="margin-bottom: 20px">
<div class="headline-bar">2015</div>
<div class="content">hello there</div>
</div>
<div class="release_holder" id="2014" style="margin-bottom: 20px">
<div class="headline-bar">2014</div>
<div class="content">hello there</div>
</div>
</form>
JavaScript Loop array that i thought of using:
var selectedText = yearSelect.options[yearSelect.selectedIndex].text;
var classList = document.getElementByClassName('press_release_holder').id.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
if (classList[i] === 'selectedText') {
//do something
}
}
Easier solution would to use querySelectorAll considering the condition of All option.
Use change listener for select-input.
var elements = document.body.getElementsByClassName("headline-bar");
var year = document.getElementById("year");
for (i = 0; i < elements.length; i++) {
var Entry = document.createElement("option");
Entry.text = elements[i].textContent;
year.add(Entry, null);
}
function showHide(elem) {
var val = elem.value;
if (val == 'All') {
[].forEach.call(document.querySelectorAll('.release_holder'), function(el) {
el.style.display = 'block';
});
} else {
[].forEach.call(document.querySelectorAll('.release_holder'), function(el) {
el.style.display = 'none';
});
document.querySelector('[id="' + val + '"]').style.display = '';
}
}
<form>
<select id="year" onchange='showHide(this)'>
<option>All</option>
</select>
<input type="submit" value="Submit">
</form>
<form action="#" id="release_year" method="post">
<div class="release_holder" id="2015" style="margin-bottom: 20px">
<div class="headline-bar">2015</div>
<div class="content">hello there</div>
</div>
<div class="release_holder" id="2014" style="margin-bottom: 20px">
<div class="headline-bar">2014</div>
<div class="content">hello there</div>
</div>
</form>
Fiddle Demo
You can use the onchange event in your drop down to fire your code:
<select onchange="myFunction()">
http://www.w3schools.com/jsref/event_onchange.asp
Then once myFunction() is fired, you get the selected text and set the CSS manually, as with this answer:
https://stackoverflow.com/a/21070237/5882767
use this on change function
<select onchange="myChangeFunction()">
function myChangeFunction(){
if( $('#year').val() == 'yourSelectedOption'){
$('.className').hide(); // use javascript function for hide show of element
}
}
Do the values of the dropdown list correspond to the year? i.e. the id of the div tag you want to hide.
If so, you can try the following:
var optionList = document.getElementById("year");
var selectedText = optionList.options[optionList .selectedIndex].value;
//hide the div with the id = selectedText
document.getElementById(selectedText).style.display = 'none';
Related
I have created a form which can be dynamically changed using the buttons included. These buttons allow for more input fields to be added/removed. The issue is that the input fields created are not posting any data/ Values in those fields not being added to the $POST array on the submit of the form.
The main functions below resposible for adding and removing rows is RemoveRows() and addRows()
What should happen is that on submit all values in the form should be "posted" then I can access all of those fields via $_POST["nameOfField"].
The way I have currently approached this is to create an input fields with the relevant id's and names then append that field to where the "hard coded" fields exists.
From my initial debugging none of the fields that have been added via javascript are in $Post which I have checked via var_dump($_REQUEST);
I have also seen that the nodes that are added are not elements of the form tag even though the nodes are added between the opening and closing tag. This can be seen in the doBeforeSubmit() Function where we can see all elements that are children of the and this never changes as rows are added/removed.
function showPlatforms() {
let nacellesOptions = ["Option1", "option2", "Option3"];
let milOptions = ["Option1", "option2", "Option3"]
let highOptions = ["Option1", "option2", "Option3"]
let entry = document.getElementById("vs")
let platfom = document.getElementById("platform")
if (platform.hasChildNodes()) {
var lastChild = platfom.lastElementChild
while (lastChild) {
platfom.removeChild(lastChild)
lastChild = platform.lastElementChild
}
}
if (entry.value == "Nacelles") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = nacellesOptions[i]
option.innerHTML = nacellesOptions[i]
platform.appendChild(option)
}
} else if (entry.value == "Military") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = milOptions[i]
option.innerHTML = milOptions[i]
platform.appendChild(option)
}
} else {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = highOptions[i]
option.innerHTML = highOptions[i]
platform.appendChild(option)
}
}
}
function formOptions() {
let entry = document.getElementById("type")
if (entry.value == "Engineering MAM") {
document.getElementById("WBS").disabled = false
document.getElementById("Desc").disabled = false
document.getElementById("ProName").disabled = false
} else {
document.getElementById("WBS").disabled = true
document.getElementById("Desc").disabled = true
document.getElementById("ProName").disabled = true
}
}
function formoptions2() {
let entry2 = document.getElementById("organisation")
if (entry2.value == "Aftermarket") {
document.getElementById("COT").disabled = false
document.getElementById("COC").disabled = false
} else {
document.getElementById("COT").disabled = true
document.getElementById("COC").disabled = true
}
}
count = document.getElementById("partNum").childElementCount
function addRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(addRow, count)
count = document.getElementById("partNum").childElementCount
//doBeforeSubmit()
}
function doBeforeSubmit() {
var es = document.getElementById("form").elements;
var l = es.length;
var msgs = [];
for (var idx = 0; idx < l; idx++) {
var e = es[idx];
msgs.push('name=' + e.name + ', type=' + e.type + ', value=' + e.value);
}
alert(msgs.join('\n'));
return false;
}
function addRow(id) {
let col = document.getElementById(id)
var box = document.createElement("INPUT")
box.setAttribute("type", "text")
box.setAttribute("id", id + count)
box.setAttribute("name", id + count)
box.setAttribute("class", "form-control")
col.appendChild(box)
}
function RemoveRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(removeBoxes)
count = document.getElementById("partNum").childElementCount
}
function removeBoxes(item) {
let box = document.getElementById(item)
let last = box.lastChild
box.removeChild(last)
}
function checkData() {
// if all stuff is correct do this:
document.getElementById("submit").disabled = false
// else dont activate the submit button.
}
<form method="post" id="form" action="SubmitMAM.php">
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNo" class="col-2">
<h3>Part Number:</h3>
</div>
<div class="col-2">
<h3>Part Description:</h3>
</div>
<div class="col-1">
<h3>Lead Time:</h3>
</div>
<div class="col-1">
<h3>Quantity:</h3>
</div>
<div class="col-1">
<h3>Date Required:</h3>
</div>
<div class="col-1">
<h3>Unit Cost:</h3>
</div>
<div class="col-2">
<h3>Unit Cost Extension:</h3>
</div>
<div class="col-1">
<h3>Unit Sale Value:</h3>
</div>
<div class="col-1">
<h3>Est Sales Value:</h3>
</div>
</div>
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNum" class="col-2">
<input type="text" id="partNum0" class="form-control" name="partNum0">
</div>
<div id="partDesc" class="col-2">
<input type="text" id="partDesc0" class="form-control" name="partDesc0">
</div>
<div id="leadTime" class="col-1">
<input type="text" id="leadTime0" class="form-control" name="leadTime0">
</div>
<div id="quantity" class="col-1">
<input type="text" id="quanitity0" class="form-control" name="quantity0">
</div>
<div id="dateReq" class="col-1">
<input type="text" id="dateReq0" class="form-control" name="dateReq0">
</div>
<div id="unitCost" class="col-1">
<input type="text" id="unitCost0" class="form-control" name="unitCost0">
</div>
<div id="unitExtention" class="col-2">
<input type="text" id="unitExtention0" class="form-control" name="unitExtention0">
</div>
<div id="unitSaleValue" class="col-1">
<input type="text" id="unitSaleValue0" class="form-control" name="unitSaleValue0">
</div>
<div id="estSalesValue" class="col-1">
<input type="text" id="estSalesValue0" class="form-control" name="estSalesValue0">
</div>
<button onclick="addRows()" class="btn btn-primary" type="button">Add a Product</button>
<button onclick="RemoveRows()" class="btn btn-primary" type="button">Remove Row</button>
<button onclick="checkData()" class="btn btn-primary" type="button">Check Data</button>
<br>
<button type="submit" name="submit" id="submit" class="btn btn-primary" disabled>Submit</button>
</form>
PHP:
<?php
var_dump($_REQUEST)
?>
UPDATE:
The code has been changed to use a php array by adding square brackets into the name which produces the following html:
<input type="text" id="partNum0" class="form-control" name="partNum[]">
<input type="text" id="partNum1" name="partNum[]" class="form-control">
<input type="text" id="partNum2" name="partNum[]" class="form-control">
You just need to use the name property of the input and add [] at the end, as GrumpyCrouton said. PHP parse it as an array, and you can access it as:
$partNum = $_POST["partNum"];
FIXED: It turns out the above code did not have any issues with the logic or the way it should work, in the source code in visual studio the indentation of some of the Divs was off causing the browser to have issues in rendering the form correctly hence why the added boxes were not included in the form and their values not POSTED.
As a heads up to anyone with maybe a similar issue, it pays to have your code neat.
I am trying to make a HTML form with a preset dropdown. The form is meant to be used frequently, so the preset menu is supposed to help the user choose common input options.
I cannot find any tutorials on how to do this anywhere, so I was hoping someone could point me in the right direction. I do not want to use any external libraries, if possible.
By a preset dropdown, I mean something like this:
var lastPreset = "preset1";
function previousPreset(element) {
lastPreset = element.value;
}
function updatePresets(element) {
var old = document.getElementById(lastPreset);
if (old) {
old.style.display = "none";
for (var i = 0; i < old.childNodes.length; i++) {
old.childNodes[i].required = false;
}
}
var preset = element.value;
var div = document.getElementById(preset);
if (div) {
div.style.display = "block";
for (var i = 0; i < div.childNodes.length; i++) {
div.childNodes[i].required = true;
}
}
lastPreset = preset;
}
function submitted() {
console.log("Submitted!");
return false;
}
#preset2, #preset3 {
display: none;
}
<form onsubmit="return submitted();">
<select onchange="updatePresets(this);" onfocus="previousPreset(this);">
<option selected value="preset1">Preset 1</option>
<option value="preset2">Preset 2</option>
<option value="preset3">Preset 3</option>
</select>
<div id="preset1">
<textarea required placeholder="Sample Text"></textarea>
</div>
<div id="preset2">
<input type="text">
</div>
<div id="preset3">
<input type="file">
</div>
<input type="submit" value="Submit">
</form>
This is just a hacky mess I made in a few minutes to show the sort of behaviour that I am trying to achieve. I am just looking for any tutorials or guides on how to do this sort of thing. It seems like someone would have tried this before.
Thanks for any responses!
I found out a far better method involving classes from looking at similar answers:
function updatePresets(element) {
var presets = document.getElementsByClassName("presets");
var div = document.getElementById(element.value);
for (var i = 0; i < presets.length; i++) {
var preset = presets[i];
preset.style.display = div === preset ? "block" : "none";
for (var j = 0; j < preset.childNodes.length; j++) {
preset.childNodes[j].required = div === preset;
}
}
}
function submitted() {
console.log("Submitted!");
return false;
}
#preset2, #preset3 {
display: none;
}
<form onsubmit="return submitted();">
<select onchange="updatePresets(this);">
<option selected value="preset1">Preset 1</option>
<option value="preset2">Preset 2</option>
<option value="preset3">Preset 3</option>
</select>
<div id="preset1" class="presets">
<textarea required placeholder="Sample Text"></textarea>
</div>
<div id="preset2" class="presets">
<input type="text">
</div>
<div id="preset3" class="presets">
<input type="file">
</div>
<input type="submit" value="Submit">
</form>
I need help extending this JavaScript (borrowed from https://www.quirksmode.org/dom/domform.html):
var appCounter = 0;
function anotherApp() {
appCounter = appCounter + 1;
var newAppField = document.getElementById("keyApp").cloneNode(true);
newAppField.id = '';
newAppField.style.display = 'block';
var newApp = newAppField.childNodes;
for (var i = 0; i < newApp.length; i++) {
var theName = newApp[i].name
if (theName) {
newApp[i].name = theName + appCounter;
}
}
var insertApp = document.getElementById('keyApp');
insertApp.parentNode.insertBefore(newAppField, insertApp);
document.getElementById('appCount').value = appCounter
}
This works fine when element in my form is:
<div id="keyApp" style="display:none">
<input type="text" name="application" id="application">
<input type="text" name="usage" id="usage">
<\div>
But when I add div's around the inputs (bootstrap styling reasons) I loose the ability to update the input names:
<div id="keyApp" style="display:none">
<div class="col-md-2">
<input type="text" name="application" id="application">
</div>
<div class="col-md-2">
<input type="text" name="usage" id="usage">
</div>
<\div>
How do I extend the script to modify the input names in these new div's?
Since there is now another layer, you need to get newApp[i].childNodes[0] now in order to get the actual input elements.
newApp now holds a list of the div elements with col-md-2 styling, and you need to get the children inside of these div elements.
I'm trying to change the option color base on an if statment. This is my form:
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
if (pro == 'Urgent') {
$("p").css('color', 'red');
}
if (pro == 'Critical') {
$("p").css('color', 'orange');
}
if (pro == 'Normal') {
$("p").css('color', 'green');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text" />
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="myFunction()">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
This if statement its what i want to do. but for now, any time im adding to the list another item with other option, all the colors are change to the last one.
you can see my problem here:
https://jsbin.com/selenifepa/edit?html,js,output
what should i do?
Use the :last-child css selector.
See this code
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
if(pro=='Urgent'){
$("p:last-child").css('color','red');
}
if(pro=='Critical'){
$("p:last-child").css('color','orange');
}
if(pro=='Normal'){
$("p:last-child").css('color','green');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text"/>
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="myFunction()">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
Instead of selecting all paragraph elements, you can select added element like this:
if(pro=='Urgent'){
$(lib).css('color','red');
}
if(pro=='Critical'){
$(lib).css('color','orange');
}
if(pro=='Normal'){
$(lib).css('color','green');
}
Replace your if with this one and this is it...
The issue is because the $('p') selector matches all existing p elements in the DOM, not just the one you added. You can fix that by using $(lib) to affect only the newly added p tag.
$(lib).css('color', 'green');
However, I would also suggest you look in to using unobtrusive event handlers as on* event attributes are considered outdated. As you're already using jQuery, here's how to do that:
$('#add').click(function(e) {
e.preventDefault();
var pro = $('#priority').val();
var $lia = $("<h5 />").text($('#task').val()).appendTo('#result');
var $lib = $("<p />").text(pro).appendTo('#priorit');
if (pro == 'Urgent') {
$lib.css('color', 'red');
}
if (pro == 'Critical') {
$lib.css('color', 'orange');
}
if (pro == 'Normal') {
$lib.css('color', 'green');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text" />
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button id="add">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
The reason is that you are selecting all the p tags with $('p'). Also, you have mixed jQuery with vanilla JS. I'll assume you want to use jQuery to simplify your code. Here it goes.
function add() {
// select the elements and assign to a var, that way we don't have to be selecting the elements over and over, which is 'slow' (research "Why traversing the DOM is slow")
var results = $('#results'),
task = $('#task'),
priority = $('#priority'),
// create the new div element with it's content
newResult = $('<div>'+task.val()+' '+priority.val()+'</div>');
// Decide what color to apply
if(priority.val() == 'Urgent'){
newResult.css('color','red');
}
if(priority.val() == 'Critical'){
newResult.css('color','orange');
}
if(priority.val() == 'Normal'){
newResult.css('color','green');
}
// append the new div to the list of results
results.append(newResult);
// clear the input and focus the cursor for the next value to be added
task.val('').focus();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text"/>
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="add()">Add</button>
<h3>List Result</h3>
<div id="results"></div>
Here This should do the trick
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
if(pro=='Urgent'){
lia.style.color='red';
lib.style.color='red';
}else{
lia.style.color='orange';
lib.style.color='orange';
}
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
document.getElementById('task').value = '';
}
The only issue was that you're selectin all the p elements by $("p"). You need to just select the currently added element i.e. lib. But lib is a javascript variable, so wrap it in jQuery to convert it into a jQuery object and then apply jQuery css.
e.g. $(lib).css('color', 'red');
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
if (pro == 'Urgent') {
$(lib).css('color', 'red');
}
if (pro == 'Critical') {
$(lib).css('color', 'orange');
}
if (pro == 'Normal') {
$(lib).css('color', 'green');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text" />
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="myFunction()">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
I have a form where I need such facility where user input some data in textfield and hits enter that time using jquery it should create new controls like new textfield, dropdown menu, textfield. and it works also, but it has a bug like when user input another data and hits enter that time value of previous controls, dropdown and textfield changes to its default.
Here is my code:
<script type="text/javascript">
function addMbo(value){
var div = document.getElementById('mboTable');
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
event.preventDefault();
var divName = document.getElementById('mboName');
var divState = document.getElementById('mboState');
var divProgress = document.getElementById('mboProgress');
divName.innerHTML = divName.innerHTML + "<input class=form-control type=text name=mboName value='" + value + "' id=mboNamw/>"
divState.innerHTML = divState.innerHTML + "<select class=form-control > <option value=1>In Progress </option><option <value=2>Completed</option><option value=3>Cancled</option></select>"
divProgress.innerHTML = divProgress.innerHTML + "<input class=form-control type=text name=progress id=progress />"
document.getElementById('mboNameInput').value = null;
}
}
</script>
HTML code:
<div class="col-sm-4">
<div class="row">
<div class="col-sm-5">
<b>Objectives</b>
</div>
<div class="col-sm-4">
<b>Status</b>
</div>
<div class="col-sm-3">
<b>Compl. %</b>
</div>
</div>
<div class="row">
<div id="mboTable">
<div id="mboName" class="col-sm-5"></div>
<div id="mboState" class="col-sm-4"></div>
<div id="mboProgress" class="col-sm-3"></div>
</div>
</div>
<div class="row" >
<div class="col-sm-5">
<input type="text" id="mboNameInput" class="form-control " onkeydown="addMbo(this.value)" placeholder="Your MBO...">
</div>
</div>
</div>
here is jsfiddle
When you do innerHTML on any element, it will completely destroy what ever content already there inside the elment.
Rather you should appndChild as shown below,
var divName = document.getElementById('mboName');
var mboName = document.createElement("INPUT");
mboName.setAttribute("type", "text");
mboName.setAttribute("class", "form-control");
divName.appendChild(mboName );
you can do the related changes to above code and make your things work.
See below code to add select dropdown.
var divState = document.getElementById('mboState');
var selectData = [{name:"In Progress",value:"1"},{name:"Completed",value:"2"},{name:"Cancelled",value:"3"}];
var selectList = document.createElement("select");
selectList.class = "form-control";
divState.appendChild(selectList);
for (var i = 0; i < selectData.length; i++) {
var option = document.createElement("option");
option.value = selectData[i].value;
option.text = selectData[i].name;
selectList.appendChild(option);
}