In my project i have a select incapsulated into two divs, i have to get the text or value) from the select from a javascript.
<div class="col-lg-3 col-xs-6" id="div1">
<div class="form-group" id="divTtype">
<label>Templte Type:</label>
<select class="form-control" id="ftype">
<option value="..All">..All</option>
<option value="Functional">Functional</option>
<option value="Non Functional">Non Functional</option>
</select>
</div>
</div>
i try this code:
function GetElementInsideContainer(containerID, childID) {
var elm = document.getElementById(childID);
var parent = elm ? elm.parentNode : {};
return (parent.id && parent.id === containerID) ? elm : {};
}
but when i try :
GetElementInsideContainer(divType, ftype).text;
an "undefined" return to me.
How can i get my select value?
so many thanks in advance
Actually there's a typo in your HTML code "divTtype", you meant to write divType
<div class="col-lg-3 col-xs-6" id="div1">
<div class="form-group" id="divType">
<label>Templte Type:</label>
<select class="form-control" id="ftype">
<option value="..All">..All</option>
<option value="Functional">Functional</option>
<option value="Non Functional">Non Functional</option>
</select>
</div>
</div>
Also you need to use textContent attribute instead of text
Finally please call the function using "id", else you are calling undefined variables divType and ftype
console.log(GetElementInsideContainer("divType", "ftype"));
This will certainly fix your current issue, although please refer to raphael answer for better approach.
Because text doesn't exist into HTMLElement.
You have to do this:
GetElementInsideContainer(divType, ftype).textContent;
Here's the documentation.
You should use quotes when you send string as a parameter:
GetElementInsideContainer('divType', 'ftype').text;
Like Krishna said in the comment above, you should be able to just do:
var select = document.getElementById('ftype')
var val = select.options[select.selectedIndex].value
You don't have to reference the parent node.
Use textContent and pass id in form of string otherwise it take it as a variable
secondly you have id divTtype and you were passing divType
function GetElementInsideContainer(containerID, childID) {
var elm = document.getElementById(childID);
var parent = elm ? elm.parentNode : {};
return (parent.id && parent.id === containerID) ? elm : {};
}
var a = GetElementInsideContainer("divType", "ftype").textContent;
console.log(a)
<div class="col-lg-3 col-xs-6" id="div1">
<div class="form-group" id="divType">
<label>Templte Type:</label>
<select class="form-control" id="ftype">
<option value="..All">..All</option>
<option value="Functional">Functional</option>
<option value="Non Functional">Non Functional</option>
</select>
</div>
</div>
Seems to be working fine overhere.
<div class="col-lg-3 col-xs-6" id="div1">
<div class="form-group" id="divTtype">
<label>Templte Type:</label>
<select class="form-control" id="ftype">
<option value="..All">..All</option>
<option value="Functional">Functional</option>
<option value="Non Functional">Non Functional</option>
</select>
</div>
</div>
<button onclick="getSelected(GetElementInsideContainer('divTtype', 'ftype'))">Get Selected Value</button>
<script>
function getSelected(objEl)
{
alert(objEl.options[objEl.selectedIndex].text);
}
function GetElementInsideContainer(containerID, childID) {
var elm = document.getElementById(childID);
var parent = elm ? elm.parentNode : {};
return (parent.id && parent.id === containerID) ? elm : {};
}
</script>
do you need the selected value of the select?
I did that snippet and get the HTML of the select.
with this snippet, you can get the value of a select
<div class="col-lg-3 col-xs-6" id="div1">
<div class="form-group" id="divTtype">
<label>Templte Type:</label>
<select class="form-control" id="ftype">
<option value="..All">..All</option>
<option value="Functional">Functional</option>
<option value="Non Functional">Non Functional</option>
</select>
</div>
</div>
function GetElementInsideContainer( childID) {
var elm = document.getElementById(childID);
console.log(elm.value)
return elm.value;
}
GetElementInsideContainer('ftype');
I think that maybe you pass in the argument an incorrect id
Related
I have an HTML form that takes in values from a dropdown list. When an option is selected the HTML badge is updated to display the status of Good or Bad.
Each badge element span class is the same, but the ID is different as I need to capture the result.
Is there a way that I can use a single JavaScript function against all span classes but only update the span class for where the dropdown box is?
Or do I need to define every element ID within the JavaScript function.
The <span class="badge badge-soft-success" is on every badge.
const changeBadgeColour = document.getElementById('project-tier-entry-level');
changeBadgeColour.addEventListener('change', function() {
var p_status = document.getElementById("project-tier-entry-level");
p_status_value = p_status.options[p_status.selectedIndex].value;
const statusBadge = document.getElementById('project-tier-entry-level-status');
if (p_status_value === "Yes") {
document.getElementById('project-tier-entry-level-status').className = 'badge badge-soft-success'
document.getElementById('project-tier-entry-level-status').textContent = 'Good!'
} else {
document.getElementById('project-tier-entry-level-status').className = 'badge badge-soft-danger'
document.getElementById('project-tier-entry-level-status').textContent = 'Bad!'
}
console.log()
});
<div class="col-sm-6">
<label class="form-label" for="project-tier-entry-level-label">Does the project land in our Tiered entry levels?</label>
<span class="badge badge-soft-success" id="project-tier-entry-level-status"></span>
<select class="form-control" name="choices-single-no-sorting" id="project-tier-entry-level">
<option value="" disabled selected hidden>Please Choose...</option>
<option>Yes</option>
<option>No</option>
</select>
</div>
You can delegate
document.getElementById('container').addEventListener('change', function(e) {
const tgt = e.target;
if (tgt.tagName === "SELECT" && tgt.id.startsWith("project-tier")) { // in case there are other things that can change in that container
const yes = tgt.value === "Yes"
const statusBadge = tgt.previousElementSibling; // or tgt.closest('div').querySelector('span.badge');
statusBadge.classList.toggle("badge-soft-success", yes)
statusBadge.classList.toggle("badge-soft-danger", !yes)
statusBadge.textContent = yes ? 'Good!' : 'Bad!';
}
});
<div id="container">
<div class="col-sm-6">
<label class="form-label" for="project-tier-entry-level-label">Does the project land in our Tiered entry levels?</label>
<span class="badge badge-soft-success" id="project-tier-entry-level-status"></span>
<select class="form-control" name="choices-single-no-sorting" id="project-tier-entry-level">
<option value="" disabled selected hidden>Please Choose...</option>
<option>Yes</option>
<option>No</option>
</select>
</div>
<div class="col-sm-6">
<label class="form-label" for="project-tier-entry-level-label">Does the project land in our Tiered normal levels?</label>
<span class="badge badge-soft-success" id="project-tier-normal-level-status"></span>
<select class="form-control" name="choices-single-no-sorting" id="project-tier-normal-level">
<option value="" disabled selected hidden>Please Choose...</option>
<option>Yes</option>
<option>No</option>
</select>
</div>
</div>
Three options with a result of the selections:
document.getElementById('container').addEventListener('change', function(e) {
const tgt = e.target;
if (tgt.tagName === "SELECT" && tgt.id.startsWith("project-tier")) { // in case there are other things that can change in that container
const badge = tgt.value
const statusBadge = tgt.previousElementSibling; // or tgt.closest('div').querySelector('span.badge');
statusBadge.classList.toggle("badge-soft-success", badge==="Yes")
statusBadge.classList.toggle("badge-soft-danger", badge==="No")
statusBadge.classList.toggle("badge-soft-unknown", badge==="Unknown")
const text = {"Yes":"Good!","No":"Bad!","Unknown":"Unknown!"}[badge] || "What?"
statusBadge.textContent = text;
const res = [...document.querySelectorAll("#container select[id^=project-tier]")]
.reduce((acc, sel) => {
if (acc[sel.value] != undefined) acc[sel.value]++;
else acc["Not set"]++;
return acc
},{"Yes":0,"No":0,"Unknown":0,"Not set":0})
document.getElementById("result").value = Object.entries(res).map(([key,val]) => `${key}: ${val}`).join('\n')
}
});
<form id="tierForm">
<div id="container">
<div class="col-sm-6">
<label class="form-label" for="project-tier-entry-level-label">Does the project land in our Tiered entry levels?</label>
<span class="badge badge-soft-success" id="project-tier-entry-level-status"></span>
<select class="form-control" name="choices-single-no-sorting" id="project-tier-entry-level">
<option value="" disabled selected hidden>Please Choose...</option>
<option>Yes</option>
<option>No</option>
<option>Unknown</option>
</select>
</div>
<div class="col-sm-6">
<label class="form-label" for="project-tier-entry-level-label">Does the project land in our Tiered normal levels?</label>
<span class="badge badge-soft-success" id="project-tier-normal-level-status"></span>
<select class="form-control" name="choices-single-no-sorting" id="project-tier-normal-level">
<option value="" disabled selected hidden>Please Choose...</option>
<option>Yes</option>
<option>No</option>
<option>Unknown</option>
<option></option>
</select>
</div>
</div>
<div>
<textarea readonly id="result"></textarea>
</div>
</form>
How about if you assign the class name directly to your changeBadgeColour variable with querySelectorAll.
const changeBadgeColour = document.querySelectorAll('.badge .badge-soft-success')
How to calculate value from different selected dropdown ?
I dont know how to show or set the value subTotal in the html or javascript.
For example, item1 will selected 2 and 1 so for the subtotal it will be 3 and the total at the end will be 3. But if the its selected 1 the total at the end will be 4.
Here my code
HTML:
<div class="class1">
<div class= "row">
<div class= "col">
<select class= "item1" onchange="update()">
<option name ="option" value="0">0</option>
<option name ="option" value="1">1</option>
<option name ="option" value="2">2</option>
</select>
</div>
</div>
<div class= "row">
<div class= "col">
<select class= "item1" onchange="update()">
<option name ="option" value="0">0</option>
<option name ="option" value="1">1</option>
<option name ="option" value="2">2</option>
</select>
</div>
</div>
<div class= "col">
<input name="subTotal1" id="subTotal1" type="text" readonly>
</div>
<div class= "row">
<div class= "col">
<select class= "item2" onchange="update()">
<option name ="option" value="0">0</option>
<option name ="option" value="1">1</option>
<option name ="option" value="2">2</option>
</select>
</div>
</div
<div class= "col">
<input name="subTotal2" id="subTotal2" type="text" readonly>
</div>
<div class= "col">
<input name="total" id="total" type="text" readonly>
</div>
</div
Javascript:
function update() {
var getAllItem1 = document.querySelectorAll(".item1");
var subTotal1 = 0;
getAllItem1.forEach(function(select) {
var valueItem1 = select.options[select.selectedIndex].value;
if (valueItem1 != 0) {
subtotal1 += parseInt(valueItem1);
}
});
document.getElementByID(".subTotal1").value = subtotal1;
}
You have a few things wrong here. Your variable subTotal1 is defined with a capital T, but when you reference it later, it is spelled subtotal1. That should be updated to match in all places referenced. Next you've used the getElementById method, but spelled it with a capital D. That should be lower case. You also left a . in front of the selector name subTotal1. An ID does not need this.
function update() {
var getAllItem1 = document.querySelectorAll(".item1");
var subTotal1 = 0;
getAllItem1.forEach(function(select) {
var valueItem1 = select.options[select.selectedIndex].value;
if (valueItem1 != 0) {
subTotal1 += parseInt(valueItem1);
}
});
document.getElementById("subTotal1").value = subTotal1;
}
Demo
And since you've tagged this as jQuery, but not used any, I've updated this using it:
function update()
{
var getAllItem1 = $(".item1");
var subTotal1 = 0;
$.each(getAllItem1, function(i, select) {
var v = $(select).val();
if (v != 0)
{
subTotal1 += parseInt(v);
}
});
$("#subTotal1").val(subTotal1);
}
$('select.item1').change(update)
Demo
I have a multidrop form at this fiddle : Here's a link! . at this form only can add multidrop 3 times, i want to make always add this multidrop, and how to save the array data into sql
<div id="Yes1">
<label for="name" >Name</label>
<input type="text" id="name1" name="name1">
<br><br>
<label for="multiDrop" >Multi Drop</label>
<select name="multiDrop1" id="multiDrop1">
<option value=""></option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
<br><br>
</div>
Check here to add and remove your elements as per your requirement.
You can remove only that block which you selected No for.
$(document).ready(function() {
$(document).on("change", ".multidrop", function() {
if ($(this).val() == 'Y') {
$clone = $(this).closest(".Yes").clone();
var num = parseInt($(".Yes:last").attr("data-index")) + 1;
$clone.attr("data-index", num);
$clone.attr("id", $clone.attr("id").replace(/\d+/, num));
$clone.find("input,select").each(function() {
var name = ($(this).attr("name")).replace(/\d+/, num);
var id = ($(this).attr("id")).replace(/\d+/, num);
$(this).attr("name", name);
$(this).attr("id", id);
});
$clone.insertAfter(".Yes:last"); //Add field html
} else if ($(this).val() == "N" && $(".Yes").length > 1) {
$(this).closest(".Yes").remove();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Yes1" class="Yes" data-index="1">
<label for="name">Name</label>
<input type="text" id="name1" name="name1" class="name">
<label for="multiDrop">Multi Drop</label>
<select name="multiDrop1" id="multiDrop1" class="multidrop">
<option value="">Select Option</option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
<br><br>
</div>
I would recommend to use following approach:
get your repetitive block HTML into a variable;
listen for changes of drop down (using event delegation, selecting by class rather than id);
modify necessary attributes (names, id's, etc) based on global counter to distinguish those dynamic blocks;
const block = `
<div class="block">
<div class="yes">
<label>Name</label>
<input type="text" class="name"></input>
<label>Multi Drop</label>
<select class="multiDrop">
<option value=""></option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
</div>
</div>
`;
const addAnotherBlock = () => {
$('#wrapper').append(block);
$('.name:last').attr('name',i++);
};
var i = 0;
$(document).ready(() => addAnotherBlock());
$('#wrapper').on('change', '.multiDrop', function(){
if($(this).val() == 'Y') addAnotherBlock();
else if($(this).val() == 'N' && $('.block').length > 1 && !$(this).closest('.block').is('.block:last')){
$(this).closest('.block').remove();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper"></div>
I have 3 HTML select under 1 div :
<div id="kurir_list">
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select disabled class="tarif">
<option select="selected"></option>
<option value="12000">JNE REGULER</option>
<option value="18000">JNE YES</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select disabled class="tarif">
<option select="selected"></option>
<option value="12000">JNE REGULER</option>
<option value="18000">JNE YES</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select disabled class="tarif">
<option select="selected"></option>
<option value="12000">JNE REGULER</option>
<option value="18000">JNE YES</option>
</select>
</div>
</div>
</div>
and I have this jquery :
$(".tarif").change(function() {
if ($(".tarif").is(':disabled')) {
alert ("yes you still have disabled element, next button disabled");
} else {
alert ("no, you don't have disabled element");
// check the other select value
$(".tarif").each(function() {
alert($(this).val());
});
}
});
every time a .tarif is selected, I need to check the other two select element value. whether it's still empty or not. but, my jquery code alert all 6 values from all select elements.
how to make jquery to be able to inform me, whether in #kurir_list still have empty select or not. thank you.
Perhaps you can try something like this, look at every select in your wrapper, if any have an empty val() then your variable will be true, in which case you can do something
var emptySelect = false;
$('#kurir_list select').each(function(){
if (!$(this).find('option:selected').val()) {
emptySelect = true;
}
});
alert(emptySelect);
<html>
<body>
<div class="block-a">
<label data-value="15" name=symptom">Group1</label>
<div class="clsfWrapper">
<label data-value="10" name=clsfName"> SubHeader1</label>
<div class="ui-select">
<div class="ui-btn">
<span>SelectedValue</span>
<select class="selectClass">
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
</select>
</div>
</div>
</div>
<div class="clsfWrapper">
<label data-value="11" name=clsfName"> SubHeader2</label>
<div class="ui-select">
<div class="ui-btn">
<span>SelectedValue</span>
<select class="selectClass">
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
</select>
</div>
</div>
</div>
</div>
<div class="block-a">
<label data-value="16" name=symptom">Group2</label>
<div class="clsfWrapper">
<label data-value="5" name=clsfName"> SubHeader1</label>
<div class="ui-select">
<div class="ui-btn">
<span>SelectedValue</span>
<select class="selectClass">
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
</select>
</div>
</div>
</div>
<div class="clsfWrapper">
<label data-value="6" name=clsfName"> SubHeader2</label>
<div class="ui-select">
<div class="ui-btn">
<span>SelectedValue</span>
<select class="selectClass">
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
</select>
</div>
</div>
</div>
</div>
</html>
</body>
What is the best way to find every select SubHeader and Group value? For example the first one:
Group value: 15
Subheader value: 10
Option value : 1
and second one:
Group value: 15
Subheader value: 11
Option value : 1
I have a very robust way to get those values and i was wondering if there was any easier and more certain way.
jQuery:
function getHtmlAttributes(){
$.each($('#page_visit_reg_new_colds_2 option:selected'), function(key, value){
var optionParent = $(this).parent();
var selectParent = optionParent.parent();
var divParent1 = selectParent.parent();
var divParent2 = divParent1.parent();
var subheaderName = divParent1.parent().find('label[name=clsfName]').data('value');
var groupName = divParent2.parent().find('label[name=symptom]').data('value');
});
EDIT Changed label value to data-value
This instead of going from the option and then with parent up to the group, will start from the block and go down to the selected option.
It is still cycling trough the elements but is not using parent()
$.each($('.block-a'), function(){
var groupName = $(this).find("label[name='symptom']").data('value');
$.each($(this).find(".clsfWrapper"), function(){
var subheaderName = $(this).find("label[name='clsfName']").data('value');
$.each($(this).find('select option:selected'), function(){
var optionvalue = $(this).val();
});
});
});
On the JSFiddle i've added console log so you can check if everything is what you expect.
Since you're using the data attribute, just use this jQuery syntax:
$("#elementName").data("DataAttribute");
To get the value from the following label (IDs are better than names):
<label data-value="11" id="clsfName"> SubHeader2</label>
Use this:
var dataValue = $("#clsfName").data("value");