Edit the Button "onclick" function depending on Selected Value - javascript

When someone clicks on the "Submit" button I would like it to call a function that is currently selected on the 'paymentMethod' option group box.
For example if I selected the Bitcoin option it will call the bitcoin() function and the button will look like this:
<button onclick='bitcoin()' class='btn btn-primary'>Submit</button>
My code:
<select class="form-control select2" id='paymentMethod'>
<optgroup label="Crypto">
<option value="Bitcoin">Bitcoin, Etherum, Litecoin, DogeCoin, Ripple, ETC</option>
</optgroup>
<optgroup label="Paypal">
<option value="Paypal">Paypal</option>
</optgroup>
<optgroup label="Giftcard">
<option value="Giftcard">Amazon, PSN, Steam, Battle.Net, G2A, ETC</option>
</optgroup>
</select>
<button onclick='//I want this to be whatever is selected in paymentMethod option group' class='btn btn-primary'>Submit</button>
I tried this JS code:
<script>
$(document).ready(function(){
$('#paymentMethod').on('change', function() {
if ( this.value == 'Paypal')
//.....................^.......
{
var paymentEr = 'Paypal()';
}
else if (this.value == 'Giftcard')
{
var paymentEr = 'Giftcard()';
} else {
var paymentEr = 'Paypal()';
}
});
});
document.write("<button onclick=' + paymentEr + "' class="btn btn-primary">Submit</button>");
</script>

Rather than change the onClick handler itself, I would make one handler that handles all of the cases (or if you want to have separate functions to organize your code, simply call those functions within the relevant condition blocks as follows):
function handleForm() {
const selected = document.getElementById("paymentMethod").value;
if (selected === 'Bitcoin') {
//handle bitcoin
}
else if (selected === 'Paypal') {
//handle Paypal
}
else if (selected === 'Giftcard') {
//handle GiftCard
}
}
<select class="form-control select2" id='paymentMethod'>
<optgroup label="Crypto">
<option value="Bitcoin">
Bitcoin, Etherum, Litecoin, DogeCoin, Ripple, ETC
</option>
</optgroup>
<optgroup label="Paypal">
<option value="Paypal">
Paypal
</option>
</optgroup>
<optgroup label="Giftcard">
<option value="Giftcard">
Amazon, PSN, Steam, Battle.Net, G2A, ETC
</option>
</optgroup>
</select>
<button onclick='handleForm()' class='btn btn-primary'>Submit</button>

On button click it checks the select element for the selected value and you can avoid inline javascript in the html code.Check my answer.
function init(){
let el = document.getElementById("paymentMethod");
let sbmBtn = document.getElementById("submitBtn");
sbmBtn.addEventListener('click',getSelectedValue);
function getSelectedValue(){
let selectedVal = el.options[el.selectedIndex].value;
if (selectedVal == 'Paypal'){
//var paymentEr = 'Paypal()';
alert(selectedVal);
}else if (selectedVal == 'Giftcard'){
//var paymentEr = 'Giftcard()';
alert(selectedVal);
} else {
//var paymentEr = 'Paypal()';
alert(selectedVal);
}
}
}
//DOM has been loaded
addEventListener('load',init);
<select class="form-control select2" id='paymentMethod'>
<optgroup label="Crypto">
<option value="Bitcoin">Bitcoin, Etherum, Litecoin, DogeCoin, Ripple, ETC</option>
</optgroup>
<optgroup label="Paypal">
<option value="Paypal">Paypal</option>
</optgroup>
<optgroup label="Giftcard">
<option value="Giftcard">Amazon, PSN, Steam, Battle.Net, G2A, ETC</option>
</optgroup>
</select>
<button id="submitBtn" class="btn btn-primary">Click</button>

Related

Make Select Menu Revert on Cancel Dialogue

I am making a system in which a user can change a select drop down and it will give them a prompt to ensure they want to take the action. Here is my code:
function changeResStatus(str1) {
var id = str1;
var status = document.getElementById("resstatus" + id).value;
var r = confirm("Change status for ID # " + id + " to " + status + "?");
if (r == true) {
console.log ("change made");
}else{
console.log ("change not made");
}
}
In the event the change is not made, I would like the select menu to go back to the previous option it was before the user attempted to change it. How would I do that?
please try this one.
$(document).on('change','.mydropdown',function(){
var previousValue = $(this).attr("data-previousvalue");
var r = confirm("Change status for");
if (r == true)
{
$(this).attr("data-previousvalue",$(this).val())
}
else
{
$(this).val($(this).attr("data-previousvalue"));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="mydropdown" data-previousvalue="0">
<option value="0">select something</option>
<option value="1">something 1</option>
<option value="2">something 2</option>
<option value="3">something 3</option>
</select>
<select class="mydropdown" data-previousvalue="0">
<option value="0">select something</option>
<option value="101">something 101</option>
<option value="102">something 102</option>
<option value="103">something 103</option>
</select>
<select class="mydropdown" data-previousvalue="0">
<option value="0">select something</option>
<option value="201">something 201</option>
<option value="202">something 202</option>
<option value="202">something 203</option>
</select>

How to make select required upon parent option selected with JavaScript or jQuery

I'm trying to make subcategory required only upon PDF option selected from the category select.
I have tried this JavaScript but its not working.
function getVal(ele){
var element = document.getElementById("category")
ele.value == "pdf" ? element.required =true : element.required =false
}
getVal(document.getElementById("subcat"))
<select id="category" name="category" required>
<option value="">select category</option>
<option>doc</option>
<option value="pdf">pdf</option>
<option>gifs</option>
</select>
<select id="subcat" name="subcat">
<option value="">select type</option>
<option>normal pdf</option>
<option>other pdf</option>
</select>
But its not working, what am I doing wrong?
using jQuery:
var $category = $("#category")
var $subcat = $("#subcat")
$category.on('change', function() {
$subcat.prop('required', $(this).val() === "pdf")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="category" name="category" required>
<option value="">select category</option>
<option>doc</option>
<option value="pdf">pdf</option>
<option>gifs</option>
</select>
<select id="subcat" name="subcat">
<option value="">select type</option>
<option>normal pdf</option>
<option>other pdf</option>
</select>
With pure JS:
var $category = document.querySelector("#category")
var $subcat = document.querySelector("#subcat")
$category.addEventListener('change', function() {
$subcat.required = this.value === "pdf"
})
This runs before the user selected something from the menu.
Adding a change event listener to the select will do it.
Also, you're mixing up ele and element.
function getVal(ele) {
ele.addEventListener('change', function() {
var element = document.getElementById("category")
element.value == "pdf" ? ele.required = true : ele.required = false
})
}
getVal(document.getElementById("subcat"))

How to disable another select option when i get value of cash from a select option

I have this code i want to enabled or disable a certain select box for transaction.
I don't know what code is correct for this one hope you can lend me a hand.
<select id="paymenttype" class="paymenttype" name="input-paymenttype" onChange="changetextbox()">
<option value="Cash">Cash</option>
<option value="Installment">Installment</option>
</select>
<select id="paymentterms" class="" name="input-paymentterms" disabled="true">
<option value="3">3x</option>
<option value="4">6x</option>
<option value="6">12x</option>
</select>
<script type="text/javascript">
function changetextbox()
{
var e = document.getElementById("paymenttype");
var value = e.options[e.selectedIndex].value;
if (value == "Cash") {
alert('I need to disable payment terms');
}
else{
alert('I need to enable payment terms');
document.getElementById("paymentterms").disable =='false';
}
}
</script>
Use this to remove attribute:
document.getElementById("paymentterms").removeAttribute("disabled");
You can use .removeAttribute() you can check it here
function changetextbox()
{
var e = document.getElementById("paymenttype");
var value = e.options[e.selectedIndex].value;
if (value == "Cash") {
alert('I need to disable payment terms');
}
else{
alert('I need to enable payment terms');
document.getElementById("paymentterms").removeAttribute('disabled');
}
}
<select id="paymenttype" class="paymenttype" name="input-paymenttype" onChange="changetextbox()">
<option value="Cash">Cash</option>
<option value="Installment">Installment</option>
</select>
<select id="paymentterms" class="" name="input-paymentterms" disabled="true">
<option value="3">3x</option>
<option value="4">6x</option>
<option value="6">12x</option>
</select>
Thank you so much for the answer. I tried and test all your answer. It is quite impressive I finish it with your help. So i decided to paste the final code here.
<select id="paymenttype" class="paymenttype" name="input-paymenttype" onChange="changetextbox()">
<option value="Cash">Cash</option>
<option value="Installment">Installment</option>
</select>
<select id="paymentterms" class="" name="input-paymentterms" disabled="true">
<option value="3">3x</option>
<option value="4">6x</option>
<option value="6">12x</option>
</select>
<script type="text/javascript">
function changetextbox()
{
var e = document.getElementById("paymenttype");
var value = e.options[e.selectedIndex].value;
if (value == "Cash") {
document.getElementById("paymentterms").disabled = true;
} else
{
document.getElementById("paymentterms").disabled = false;
}
}
</script>

Change select box value depending other selected option box

i am new to Javascript/ Jquery
so my problem is :
i want to change the select/option box text and value depending on the other selected option/box
so for examplemy first option is :
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
and then one i want to change depending on selected option is :
When its male :
<select id="name">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
when its female :
<select id="name">
<option>Select Your Name</option>
<option value="female1">Female 1</option>
<option value="female2">Female 2</option>
</select>
Thanks for the help! :)
There you go with DEMO
var options=""; //store the dynamic options
$("#gender").on('change',function(){ //add a change event handler to gender select
var value=$(this).val(); //get its selected value
options="<option>Select Your Name</option>"
if(value=="Male") //value ==Male then set male required options
{
options+="<option value='Male1'>Male 1</option>"
+"<option value='Male2'>Male 2</option>";
$("#name").html(options);
}
else if(value=="Female") //else set female required options
{
options+='<option value="female1">Female 1</option>'
+'<option value="female2">Female 2</option>';
$("#name").html(options);
}
else
$("#name").find('option').remove() //if first default text option is selected empty the select
});
I would suggest to have a better HTML architecture to achieve this kind of things. Have each name in one Dropdown only and categorise with some data attribute. When changing the value of Gender Dropdown, filter with type and toggle the options. Follow this:
$(function(){
$("#gender").on("change", function(){
var $target = $("#name").val(""),
gender = $(this).val();
$target
.toggleClass("hidden", gender === "")
.find("option:gt(0)").addClass("hidden")
.siblings().filter("[data-type="+gender+"]").removeClass("hidden");
});
});
.hidden{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="gender">
<option value="">Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="name" class="hidden">
<option value="">Select Your Name</option>
<option value="Male1" data-type="Male">Male 1</option>
<option value="Male2" data-type="Male">Male 2</option>
<option value="female1" data-type="Female">Female 1</option>
<option value="female2" data-type="Female">Female 2</option>
</select>
Fiddle link: http://jsfiddle.net/ashishanexpert/qzxedcut/
Whenever a change occurs, use the value of the gender dropdown to populate the names one. We use a for loop to produce more than one option per gender.
$('#gender').change(function(){
if(!this.selectedIndex) return;
var gender = $(this).val(),
$name = $('#name').empty(),
$option = $('<option />').text('Select Your Name').appendTo($name);
for(var i = 1; i <= 2; i++)
$option.clone().prop('value', gender + i).text(gender + ' ' + i).appendTo($name);
});
JSFiddle
Follow the Practice:
Do not hardcode options this case.Best practice is get value from Json.
Then later changes are easy instead of change all codings.
Build dynamic Dropdowns. Dont Hide and Show.
HTML
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="gtr" name="location" placeholder="Anycity"></select>
Jquery
jQuery(function($) {
var gender = {
'Male': ['Male1', 'male2'],
'Female': ['Female1','Female1'],
}
var $gndr = $('#gtr');
$('#gender').change(function () { debugger
var GNDR = $(this).val(), gndrs = gender[GNDR] || [];
var html = $.map(gndrs, function(gndr){
return '<option value="' + gndr + '">' + gndr + '</option>'
}).join('');
$gndr.html(html);$gndr.append(new Option("Select Name", "0"));$gndr.val("0");
});
});
JsFiddle
https://jsfiddle.net/2pza5/1135/
I suggest you to try this way:
Change you jquery:
<select id="nameMale">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
<select id="nameFemale">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
Inser this javascript:
<script>
<![CDATA[
$(function() {
$('#nameFemale').hide();
$('#nameMale').hide();
function changeGen(val){
if(val == 'Female'){
$('#nameFemale').show();
$('#nameMale').hide();
}else{
$('#nameFemale').hide();
$('#nameMale').show();
}
}
$('#gender').change(function() {
changeGen($('#gender').val());
});
});
]]>
</script>
FIDDLE
$('#gender').change(function (e) {
var val = $("option:selected", this).val()
console.log(val);
if(val =='Male'){
$('#name').find('option.female').hide();
$('#name').find('option.male').show();
}else if(val =='Female'){
$('#name').find('option.female').show();
$('#name').find('option.male').hide();
}else{
}
});
Added class for each option since it is static.
Then you can hide the option from second select depending on the value of first select
Try this:
$("#gender").on("change",function(){
var sel="";
if($(this).val() == "Female"){
sel=' <option>Select Your Name</option>';
sel+=' <option value="female1">Female 1</option>'
sel+='<option value="female2">Female 2</option>'
}else{// no other if since you have only two options male/female
sel= '<option>Select Your Name</option>';
sel+= '<option value="Male1">Male 1</option>';
sel+= '<option value="Male2">Male 2</option>';
}
$("#name").html(sel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="name">
</select>

Compare select values and show alert if they match

I have 4 dropdowns from which you have to select an option.
What I am trying to do is show an alert if you chose the same option more than once. Its purpose is to keep the score for a game so a person shouldn't be able to play as 2.
At the moment the dropdown looks like this:
<select id="users_1" aria-labelledby="dropdownMenu1">
<option>Select player</option>
<?php foreach($users as $user) : ?>
<option value="<?=$user['id_user']?>"><?=$user['nume']?></option>
<?php endforeach; ?>
</select>
And what I've tried to do in JQuery is this:
$("#users_2").change(function() {
var a=$(this).val("#users_1");
var b=$(this).val("#users_2");
if(a == b) {
alert($(this).val());
}
});
And I also tried to compare them like this:
$("#users_2").change(function() {
if($(this).val() == $("#users_1").val()) {
alert($(this).val());
}
});
None seems to work and I have no clue why. I've checked and the actual values are taken from the view but the if clause cannot compare them apparently.
Thank you for any help! Much appreciated!
Get your values, don't set them
Change this…
$("#users_2").change(function() {
var a=$(this).val("#users_1");
var b=$(this).val("#users_2");
if(a == b) {
alert($(this).val());
}
});
…to this…
$("#users_2").change(function() {
var a = $("#users_1").val();
var b = $(this).val(); // equivalent to $("#users_2").val()
if(a === b) { // Use strict comparison operator as a best practice
alert(a + ' matches ' + b);
}
});
Make it dynamic
You can take it a step farther by listening to a set of elements and making your handler dynamic:
// Listen to set of all select elements.
$('select').on('change', function(e) {
// Serialize form values.
var vals = $('#select_player').serializeArray();
// Convert to simple array of just values.
vals = $.map(vals, function (val, i) {
return val.value;
});
// Remove current selection from array…
vals.splice(vals.indexOf($(this).val()), 1);
// …then check to see if it's value was already there.
if(vals.indexOf($(this).val()) !== -1) { // If value is found,
// …reset current select element to default option,
$(this).val('default');
// …and alert user with a relevant message.
alert('You cannot select this player more than once.');
};
});
label {
display: block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="select_player" name="select_player">
<label>Player 1:
<select id="users_1" name="users_1">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 2:
<select id="users_2" name="users_2">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 3:
<select id="users_3" name="users_3">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 4:
<select id="users_4" name="users_4">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
</form>
I used the same class on all the dropdowns and then use only one event handler.
$('.dropdown').on('change', function (event) {
var selectedValue = $(event.currentTarget).val();
var matchedDropdowns = $('.dropdown').filter(function (index) {
return $(this).val() === selectedValue;
});
if (matchedDropdowns.length > 1) {
alert("Alert Alert!")
}
})
In the event handlers I can get the selected value, filter all the dropdowns that match that value and if I get more than 1 dropdown I will just show the alert.
You can check it on fiddle.

Categories

Resources