How to get options element by id and output text - javascript

Could someone help me with this little javascript. I want the rersult to show in NA only when option value 2 is selected. I want 11" to show will show. Need a simple script to output custom text based on value text. I do know i have value="2" listed twice. I cannot use the value field.
<select id="sizing-change" onchange="myFunction()">
<option value="2">12"</option>
<option value="2" id="test">11"</option>
</select>
<div class="sizefinal">
Suggested Size: <span id="finalsize">NA</span>
</div>
<script>
function myFunction() {
if(document.getElementById("test").value == "11") {
document.getElementById("finalsize").innerHTML = "Size: 11";
}
}
</script>

You can check the text of the option like
function myFunction() {
var el = document.getElementById("sizing-change");
if (el.options[el.selectedIndex].text.trim() == '11"') {
document.getElementById("finalsize").innerHTML = "Size: 11";
} else {
document.getElementById("finalsize").innerHTML = "NA";
}
}
<select id="sizing-change" onchange="myFunction()">
<option value="2">12"</option>
<option value="2" id="test">11"</option>
</select>
<div class="sizefinal">
Suggested Size: <span id="finalsize">NA</span>
</div>

If you can alter the value field of option to different values(which you should) then you can try this:
<select id="sizing-change" onchange="myFunction()">
<option value="12">12</option>
<option value="11" id="test">11</option>
</select>
<div class="sizefinal">Suggested Size: <span id="finalsize">NA</span>
</div>
<script>
function myFunction() {
if (document.getElementById("sizing-change").value == 11) {
document.getElementById("finalsize").innerHTML = "Size: 11";
}
}
</script>
Demo: http://jsfiddle.net/GCu2D/784/

var finalsize = document.querySelector('#finalsize');
var sizingChange = document.querySelector('#sizing-change')
var testOption = sizingChange.querySelector('#test');
myFunction(sizingChange);
function myFunction(element) {
var checked = element.querySelector(':checked');
if (checked == testOption) {
finalsize.innerHTML = "Size: " + element.querySelector(':checked').text;
} else {
finalsize.innerHTML = 'NA';
}
}
<select id="sizing-change" onchange="myFunction(this)">
<option value="2">12"</option>
<option value="2" id="test">11"</option>
</select>
<div class="sizefinal">
Suggested Size: <span id="finalsize">NA</span>
</div>

Related

How to have access inside div element?

i am trying to create simple Rock,paper, scissor game,
but i have some case, i want to have access on div which id is firstplayer, also this div has increment function, which increases value by 1... if in form field i choose 12, an when i press "firstplayer" and it value will increase to 12, i want to console.log("you win"), i tried a lot, but it's not works, what can i do, to solve this problem?
<!-----my html---->
<form action="#">
<label for="numbers">Game up to:</label>
<select id="form" >
<option value="7" >7</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<input type="submit" id="submit">
</form>
<div>
<h4 onclick="increment()">Firstplayer</h4>
<div id="firstplayer">
</div>
</div>
///my js
const firsPlayer = document.getElementById("firstplayer");
const Form = document.getElementById("submit");
form.addEventListener("input", function(event){
event.preventDefault();
if (event.target.value==="12"){
return playerwin()
}
})
var x=0;
function increment(){
return firsPlayer.innerHTML = ++x;
}
// i tried this but it's not working
function playerwin(){
if(firsPlayer.childNodes[0].nodeValue == 12){
console.log("you win")
}
}
my code here https://codepen.io/kafka2001/pen/LYpmexe
Not exactly sure what the final result should be but please check the code below that illustrates how it could basically work. Just adapt it to your needs to obtain the desired result.
const firsPlayer = document.getElementById("firstplayer");
const select = document.getElementById("select");
var x = 0;
function increment() {
firsPlayer.innerHTML = Number(firsPlayer.innerHTML) + 1;
}
function addSelected() {
firsPlayer.innerHTML = Number(firsPlayer.innerHTML) + Number(select.value);
}
function playerwin() {
if (firsPlayer.childNodes[0].nodeValue == 12) {
console.log("you win")
}
}
<select id="select">
<option value="7">7</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<input type="button" onClick="increment();" value="Increment">
<div>
<h4 onclick="addSelected()">Firstplayer</h4>
<div id="firstplayer"></div>
</div>

Output text changes based on two drop down menus

So basically I am trying to make a page where the user can select options from two drop down menus, when the second drop down menu has been completed and both have options in them I want it to trigger some javascript that takes those values and then returns text depending on the output.
E.g. a user selects xbox and comfort trade, the price is returned as £5, or maybe they select playstation and comfort trade, the price is returned as £2.50, or maybe they want pc and player auction the price is only £0.99.
HTML
<select id="platform" name="platform">
<option select value=""></option>
<option value="xbox">Xbox</option>
<option value="playstation">PlayStation</option>
<option value="pc">PC</option>
</select><br>
<p>Select Method:</p>
<select id="method" name="method" onChange="price()">
<option selected value=""></option>
<option value="comfortTrade">Comfort Trade</option>
<option value="playerAuction">Player Auction</option>
</select><br>
<h3 id="price"></h3>
Javascript
function price() {
if ($(document.getElementById("platform")) === "xbox" && $(document.getElementById("method")) === "comfortTrade") {
document.getElementById("price").innerHTML = "£5";
} else if ($(document.getElementById("platform")) === "playstation" && $(document.getElementById("method")) === "comfortTrade") {
document.getElementById("price").innerHTML = "£2.50";
}
}
I'm quite new to Javascript but I had a go at doing this, I also have spent the past hour or so trying to search for tutorials on this but nothing got it to work.
Try with this javascript function:
function price() {
if (document.getElementById("platform").value == "xbox" && document.getElementById("method").value == "comfortTrade") {
document.getElementById("price").innerHTML = "£5";
} else if (document.getElementById("platform").value == "playstation" && document.getElementById("method").value == "comfortTrade") {
document.getElementById("price").innerHTML = "£2.50";
}
}
A couple things need to be updated in the existing code to get this to work:
1) onchange has no capital letters, and needs to be added to "platform" <select> as well
2) no need for $ here, can simply use document.getElementById
3) after selecting the element in step 2, will need to get the value of the select by accessing the property .value on the element.
Fixed code:
<div id="app">
<select id="platform" name="platform" onchange="price()">
<option select value=""></option>
<option value="xbox">Xbox</option>
<option value="playstation">PlayStation</option>
<option value="pc">PC</option>
</select><br>
<p>Select Method:</p>
<select id="method" name="method" onchange="price()">
<option selected value=""></option>
<option value="comfortTrade">Comfort Trade</option>
<option value="playerAuction">Player Auction</option>
</select><br>
<h3 id="price"></h3>
</div>
<script>
function price() {
if(document.getElementById("platform").value === "xbox" && document.getElementById("method").value === "comfortTrade") {
document.getElementById("price").innerHTML = "£5";
} else if(document.getElementById("platform").value === "playstation" && document.getElementById("method").value === "comfortTrade") {
document.getElementById("price").innerHTML = "£2.50";
}
}
</script>
Presuming you have jQuery installed because you are using $(...) in your code, you can solve your issue like this:
<select id="platform" name="platform" onchange="findPrice()">
<option select value=""></option>
<option value="xbox">Xbox</option>
<option value="playstation">PlayStation</option>
<option value="pc">PC</option>
</select><br>
<p>Select Method:</p>
<select id="method" name="method" onchange="findPrice()">
<option selected value=""></option>
<option value="comfortTrade">Comfort Trade</option>
<option value="playerAuction">Player Auction</option>
</select><br>
<h3 id="price"></h3>
<script type="application/javascript">
window.findPrice = function() {
if($("#platform").val() === "xbox" && $("#method").val() === "comfortTrade") {
document.getElementById("price").innerHTML = "£5";
}else if($("#platform").val() === "playstation" && $("#method").val() === "comfortTrade") {
document.getElementById("price").innerHTML = "£2.50";
}
}
</script>
You can see a working example of this at: https://jsfiddle.net/L2vgqmtL/
However, I would actually propose a slightly different solution that I find more elegant:
<script type="application/javascript">
window.findPrice = function() {
var platform = $("#platform").val();
var method = $("#method").val();
var priceUpdateText = "";
if(method == 'comfortTrade'){
switch(platform){
case "xbox":
priceUpdateText = "£5";
break;
case "playstation":
priceUpdateText = "£2.50";
break;
default:
priceUpdateText = "";
}
}
$("#price").text(priceUpdateText);
}
</script>
<select id="platform" name="platform" onchange="findPrice()">
<option select value=""></option>
<option value="xbox">Xbox</option>
<option value="playstation">PlayStation</option>
<option value="pc">PC</option>
</select><br>
<p>Select Method:</p>
<select id="method" name="method" onchange="findPrice()">
<option selected value=""></option>
<option value="comfortTrade">Comfort Trade</option>
<option value="playerAuction">Player Auction</option>
</select><br>
<h3 id="price"></h3>
A working example of this solution is available here: https://jsfiddle.net/8wafskbw/2/
Important Note: Both of these solutions operate under the presumption that have jQuery included in your page.

Verify values of selctbox using jquery

i'm new to this. I'm using in a html page with 2 selctboxs, one for min price and the other for max price and a hidden input to put on it the combination of the two values of the selectboxs.
<div class="option-bar mini first">
<label><?=__("Min Price")?></label>
<span class="selectwrap">
<select name="min-price" id="pmin" class="search-select">
<option value=""></option>
<option value="1000">$1000</option>
<option value="2000">$2000</option>
<option value="3000">$3000</option>
<option value="4000">$4000</option>
<option value="5000">$5000</option>
<option value="6000">$6000</option>
<option value="7000">$7000</option>
<option value="8000">$8000</option>
<option value="9000">$9000</option>
</select>
</span>
</div>
<div class="option-bar mini">
<label><?=__("Max Price")?></label>
<span class="selectwrap">
<select name="max-price" id="pmax" class="search-select">
<option></option>
<option value="2000">$2000</option>
<option value="3000">$3000</option>
<option value="4000">$4000</option>
<option value="5000">$5000</option>
<option value="6000">$6000</option>
<option value="7000">$7000</option>
<option value="8000">$8000</option>
<option value="9000">$9000</option>
<option value="10000">$10,000</option>
</select>
</span>
</div>
<input type="hidden" id="prix" name="prix" class="sel2" value="" />
and i got this jquery code :
$("#pmin, #pmax").change(function(){
update();
});
function update() {
$("#prix").val($('#pmin').val() + "-" + $('#pmax').val());
}
So what i want to do is when the user select options in the two selectbox, verify if the min price value is lower than the max price value and if not show a message.
Thnx a lot guys.
$("#pmin, #pmax").change(function() {
if ($("#pmin").val() && $("#pmax").val()) { //check if both have values
if (parseFloat($("#pmin").val()) > parseFloat($("#pmax").val())) { //check if valid range
alert('invalid range')
return;
}
}
update();
});
$(".search-select").change(fucntion(){
var max_val = $("#pmax").val();
var min_val = $("#pmin").val();
if(max_val != '' && min_val != '' && max_val < min_val){
alert("Max value is less than Min value.");
}
});
Try this..!!
You should modify the change and update method as shown below:
$("#pmin, #pmax").change(function() {
if ($('#pmin').val() != "" && $('#pmax').val() != "") {
update();
}
});
function update() {
var computedValue = parseInt($('#pmin').val()) - parseInt($('#pmax').val());
if (computedValue < 0) {
alert('Invalid selection.');
}
$("#prix").val(computedValue);
}
Refer the demo.

div inside form not being 'seen'

I have a div inside my form which is filled with a field based on the value of the select box above it. This field always comes back as 'null' when submitted, I put a div around other parts of the form to test if it was in fact the div itself and each field with a div around it kept coming back as 'null'.
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<!--This div below is called every time I want to add a new 'instance' of this form
this div works fine, its when i add a div inside that one I get 'null'-->
<div id="readnode" style="display: none">
<select name="rank">
<option disabled="disabled" selected="selected">Rating</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<select name="time">
<option disabled="disabled" selected="selected">Time</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<input type="button" value="X"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
So the code above works fine its when i add a div inside i get 'null' like below;
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<!--This div below is called every time I want to add a new 'instance' of this form
this div works fine, its when i add a div inside that one I get 'null'-->
<div id="readnode" style="display: none">
<select name="rank">
<option disabled="disabled" selected="selected">Rating</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<div id='testdiv'>
<select name="time">
<option disabled="disabled" selected="selected">Time</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
</div>
<input type="button" value="X"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
Whats my best way around this? and how would I go about doing it?
EDIT: The Div 'readnode' is called and placed inside the form when needed, replacing the div 'writenode' which is seen inside the form above. This div works perfectly fine. When i add another div (testdiv) inside the 'readnode' any fields placed inside the new div (testdiv) always come back as null when using $_get.
EDIT2:
Function that puts the readnode in place of the writenode,
<script type="text/javascript">
/* Set the counter that will increase every time
the user adds a new language*/
var counter = 0;
function addlanguage()
{
// Ask the user for input
var language = prompt("Language Name","");
if (language == "" || language == null)
{
alert("Please enter a language.");
}
else
{
counter++;
// Find the element to be copied
var newNode = document.getElementById('readnode').cloneNode(true);
newNode.id = '';
newNode.style.display = 'block';
var newField = newNode.childNodes;
// Give all fields a unique value
for (var i=0;i<newField.length;i++)
{
var theName = newField[i].name;
var theId = newField[i].id;
if (theName)
{
newField[i].name = theName + counter;
}
if (theId == "languagename")
{
// Change the field to the user input
newField[i].innerHTML = language;
}
if (theName == "lang")
{
// Replace the hidden field with the correct language
newField[i].value = language;
}
}
// Insert the elements
var insertHere = document.getElementById('writenode');
insertHere.parentNode.insertBefore(newNode,insertHere);
}
}
</script>
and this is the php;
<?php
if ($_GET["time1"] == null)
{ ?>
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<?php
}
else
{
$final = 0;
$i = 1;
while($final == 0)
{
$gettime = "time" . $i;
$getRank = "rank" . $i;
$time = $_GET[$gettime];
$rank = $_GET[$getRank];
if ($language == "")
{
$final = 1;
}
if ($final == 0)
{
// Show the user the input
echo("<p>Your <strong>$time</strong> is <strong>$rank</strong>.</p>");
}
$i++;
}
} ?>
When you put it inside a div, it's no longer part of newNode.childNodes, so you never get to set the name properly. You'll have to check childs of childs or use jQuery to simplify things.
for (var i=0;i<newField.length;i++)
{
var subField = newField.childNodes;
for (var i=0;i<subField.length;i++) {
var theName = subField[i].name;
var theId = subField[i].id;
// ...
}
}

javascript dropdown validation

I need to alert if you haven't selected anything and couldn't get it to work. It needs to show what is where wrong and alert with a window.
<!DOCTYPE html>
<html>
<head>
<select id="ddlView">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<input type="button" onclick="myFunction()" value="select" />
<script>
function Validate()
{
var e = document.getElementById("ddlView");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0)
{
alert("Please select a user");
}
}
</td></head>
</html>
I think you have multiple problems here.
You need to add a body tag
Set the correct function name in your button.
you need a closing script tag
Give this a try:
<!DOCTYPE html>
<html>
<body>
<select id="ddlView">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<input type="button" onclick="Validate()" value="select" />
<script type="text/javascript">
function Validate()
{
var e = document.getElementById("ddlView");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0)
{
alert("Please select a user");
}
}
</script>
</body>
</html>
This is not you asked for but you can still consider what i did.
Have an option with value 0 which is going to be the default option of the dropdown and add required attribute to the select element.
Once this select element is in a form and is submitted ,HTML is automatically going to take over the validation part.
<select required>
<option value="">Select</option>
<option value="1">Option1</option>
</select>
<body>
<div>
<span>Select the course : </span>
<select id="ddlView">
<option value="0">Select</option>
<option value="1">Java Script</option>
<option value="2">CSS</option>
<option value="3">JQuery</option>
<option value="3">HTML</option>
<option value="3">C#</option>
</select>
</div>
<br >
<input type="button" class="btn" value="Submit" id="btnSubmit" onclick="ddlValidate();" />
<script type="text/javascript">
function ddlValidate() {
var e = document.getElementById("ddlView");
var optionSelIndex = e.options[e.selectedIndex].value;
var optionSelectedText = e.options[e.selectedIndex].text;
if (optionSelIndex == 0) {
alert("Please select a Course");
}
else {
alert("Success !! You have selected Course : " + optionSelectedText); ;
}
}
</script>
That has to be in your form processing script, you can just add it to the top of your code and check if it has been submitted.
// Place this atop of your script.
if(isset($_POST)) {
if($_POST['member_id']) {
// Your codes here
}
}
call this function at a button click(OnClientClick=" return Validate()") you have to list an item for the 0'th positions(ddlView.Items.Insert(0, new ListItem("Select...", "0"));)
function Validate(){
var region = document.getElementById('<%=ddlView.ClientID%>').value;
if (region == 0) {
alert("Please select a user");
return false;
}
}

Categories