<select data-placeholder="Please select a payment method.." style="width:50%;" class="chosen" onchange="currencyChange(this.value)">
<option value=""></option>
<optgroup label="Cash">
<option value="Paypal">Paypal</option>
<option value="Bitcoin">Bitcoin</option>
<option value="Western Union">Western Union</option>
<option value="Delivery">Delivery</option>
</optgroup>
<optgroup label="Ingame Currency">
<option value="RS3 GP">RS3 GP</option>
<option value="OSRS GP">OSRS GP</option>
</optgroup>
</select>
<script type="text/javascript">
var sign = "null";
var placement = "null";
float budget = "null";
function currencyChange(data){
if (data === 'Paypal') {
sign = "$";
placement = "before";
}
if (data === 'Bitcoin') {
sign = "$";
placement = "before";
}
if (data === 'Western Union') {
sign = "$";
placement = "before";
}
if (data === 'Delivery') {
sign = "$";
placement = "before";
}
if (data === 'RS3 GP') {
sign = "M/GP";
placement = "after";
}
if (data === 'OSRS GP') {
sign = "M/GP";
placement = "after";
}
if (placement === 'before') {
document.getElementById("budget").value = sign + document.getElementById("budget").value;
}
if (placement === 'after') {
document.getElementById("budget").value = document.getElementById("budget").value + sign;
}
}
</script>
I am trying to change the currency type of another textfield id="budget" to add a currency symbol dependent on the choice of payment method..?
But I get no such action when selecting the payment type.
remove this, Its works
float budget = "null";
And,
add below select
<input type="text" id="budget">
Edited
if (placement === 'before') {
toreplaceaft=document.getElementById("budget").value;
toreplacebef=toreplaceaft.replace("$","");
toreplace=toreplacebef.replace("M/GP","");
document.getElementById("budget").value = sign + toreplace.replace("$","");
}
if (placement === 'after') {
toreplaceaft=document.getElementById("budget").value;
toreplacebef=toreplaceaft.replace("$","");
toreplace=toreplacebef.replace("M/GP","");
document.getElementById("budget").value = toreplace+ sign;
}
Try this fiddle it will not accepting double sign.
http://jsfiddle.net/pee7d6qr/1/
if (placement === 'before') {
if(document.getElementById("budget").value.indexOf("$") == -1){
document.getElementById("budget").value = sign + document.getElementById("budget").value;
}
else {
document.getElementById("budget").value = document.getElementById("budget").value;
}
}
if (placement === 'after') {
if(document.getElementById("budget").value.indexOf("M/GP") == -1){
document.getElementById("budget").value = document.getElementById("budget").value + sign;
}
else {
document.getElementById("budget").value = document.getElementById("budget").value;
}
}
Remove the float variable in javascript
Budget Input element is missing
<input type="text" name="budget" id="budget" value=>
Use the below code
if (placement === 'before') {
document.getElementById("budget").value = sign + document.getElementById("budget").value.replace(/[^0-9.]/g,'');
}
if (placement === 'after') {
document.getElementById("budget").value = document.getElementById("budget").value.replace(/[^0-9.]/g,'') + sign;
}
Now you need to strip those "$,M/GP" stuff from the string
With little help from stackoverflow:
value = document.getElementById("budget").value;
value = value.replace(/\D/g,''); //strip non-numeric characters from string
Then
if (placement === 'before') {
document.getElementById("budget").value = sign +" "+ value;
}
if (placement === 'after') {
document.getElementById("budget").value = value +" "+ sign;
}
jsFiddle
Related
I'm trying to validate my form using jquery before submission. The user needs to fill up the Task accordingly, they cannot submit the form with fill-up Task 2 and missing Task 1. And also the Task cannot be duplicated with other Task. I'm wondering if there any better way to compare all of this, in a simple method.
The Javascript currently I'm doing. Still not complete yet because looking for better ways.
$(function() {
$( "#create_model" ).submit(function( event ) {
if(validate_task()){
alert("Check your task.");
event.preventDefault();
} else {
$("#create_model").submit();
}
});
});
function validate_task() {
if ($('#CatTask2ID').val() !== "" && $('#CatTask2ID').val() === "") {
return "Task 1 is empty"; //return FALSE;
} else if ($('#CatTask3ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "") {
return "Task 1 or 2 is empty"; //return FALSE;
} else if ($('#CatTask4ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask5ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "" || $('#CatTask4ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask5ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "" || $('#CatTask4ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask1ID').val() === $('#CatTask2ID').val() || $('#CatTask1ID').val() === $('#CatTask3ID').val() .......and others........... ) {
return "Duplicates"; //return FALSE;
}
}
First use classes instead of IDs so you can get a collection of all selects easily, then map each select to its value to get an array of values.
Find the index of the first value which is the empty string. If any values after that one are populated, return an error saying that the index of that empty string is empty.
Otherwise, take the populated values (from indices 0 to the index of the first empty string), and check if the size of a Set of those values is equal to the length of the array:
function validate_task() {
const taskValues = [...$('.tasks')].map(task => task.value);
const firstEmptyIndex = taskValues.indexOf('');
if (firstEmptyIndex > 0 && taskValues.slice(firstEmptyIndex).some(val => val)) {
return `Task ${firstEmptyIndex + 1} is empty`;
}
const populatedTasks = taskValues.slice(0, firstEmptyIndex);
if (populatedTasks.length !== new Set(populatedTasks).size) {
return 'Duplicates';
}
// OK
}
Live demo:
document.addEventListener('change', () => console.log(validateTask()));
function validateTask() {
const taskValues = [...$('.tasks')].map(task => task.value);
const firstEmptyIndex = taskValues.indexOf('');
if (firstEmptyIndex !== -1 && taskValues.slice(firstEmptyIndex).some(val => val)) {
return `Task ${firstEmptyIndex + 1} is empty`;
}
const populatedTasks = taskValues.slice(0, firstEmptyIndex);
if (populatedTasks.length !== new Set(populatedTasks).size) {
return 'Duplicates';
}
return 'OK'
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
function validate_task() {
var error_msg = [];
if($('#CatTask1ID').val() === ""){
error_msg.push('1');
}
if($('#CatTask2ID').val() === ""){
error_msg.push('2');
}
if($('#CatTask3ID').val() === ""){
error_msg.push('3');
}
//......
return error_msg;
}
function validate_task_msg() {
var arr = validate_task()
if(arr&& arr.length<=0){
return true;
}else if(arr.length == 10){//more
return "Duplicates";
}else {
var msg = arr.join(',');
return "Task "+ msg + " is empty"
}
}
I created a calculator using HTML and JavaScipt. The calculator works, so that is fine. However, I would like to write a message in the html that lets the user know they have to enter a variable, if the result is NaN. While I know I need to use a conditional statement, I am not sure how to code it.
Here is my code:
function calc(){
var n1 = parseFloat(document.getElementById("n1").value);
var n2 = parseFloat(document.getElementById("n2").value);
var oper = document.getElementById("operators").value;
if( oper === "+"){
document.getElementById("result").value = n1+n2;
}
if( oper === "-"){
document.getElementById("result").value = n1-n2;
}
if( oper === "*"){
document.getElementById("result").value = n1*n2;
}
if( oper === "/"){
document.getElementById("result").value = n1/n2;
}
if( oper === NaN ){
document.getElementById("Comments").innerHTML= "Write something in the boxes, you silly ass." ;
}
}
<input type="text" id="n1"/><br/><br/>
<input type="text" id="n2"/><br/><br>
<select id="operators">
<option value="+">+</option>
<option value="-">-</option>
<option value="X">X</option>
<option value="/">/</option>
</select>
<input type="text" id="result"/>
<button onclick="calc();">=</button>
<p id="Comments"></p>
To improve your code you can add else if and isNaN, like this:
function calc(){
var n1 = parseFloat(document.getElementById("n1").value);
var n2 = parseFloat(document.getElementById("n2").value);
var oper = document.getElementById("operators").value;
if( oper === "+"){
document.getElementById("result").value = n1+n2;
} else if( oper === "-"){
document.getElementById("result").value = n1-n2;
} else if( oper === "*"){
document.getElementById("result").value = n1*n2;
} else if( oper === "/"){
document.getElementById("result").value = n1/n2;
} else if( isNaN(oper) ){
document.getElementById("Comments").innerHTML= "Write something in the boxes, you silly ass." ;
}
}
<input type="text" id="n1"/><br/><br/>
<input type="text" id="n2"/><br/><br>
<select id="operators">
<option value="+">+</option>
<option value="-">-</option>
<option value="X">X</option>
<option value="/">/</option>
</select>
<input type="text" id="result"/>
<button onclick="calc();">=</button>
<p id="Comments"></p>
Use the isNaN function to check for it
function calc(){
var n1 = parseFloat(document.getElementById("n1").value);
var n2 = parseFloat(document.getElementById("n2").value);
var oper = document.getElementById("operators").value;
if( oper === "+"){
document.getElementById("result").value = n1+n2;
}
if( oper === "-"){
document.getElementById("result").value = n1-n2;
}
if( oper === "*"){
document.getElementById("result").value = n1*n2;
}
if( oper === "/"){
document.getElementById("result").value = n1/n2;
}
if( isNaN(oper) ){
document.getElementById("Comments").innerHTML= "Write something in the boxes, you silly ass." ;
}
}
<input type="text" id="n1"/><br/><br/>
<input type="text" id="n2"/><br/><br>
<select id="operators">
<option value="+">+</option>
<option value="-">-</option>
<option value="X">X</option>
<option value="/">/</option>
</select>
<input type="text" id="result"/>
<button onclick="calc();">=</button>
<p id="Comments"></p>
I'll provide this as a more concise version. There's no reason to select an element more than once if you plan on altering it later. Using the object as a container for your options allows you to validate and execute a bit easier.
const options = {
'+'(a, b) { return a + b },
'-'(a, b) { return a - b },
'*'(a, b) { return a * b },
'/'(a, b) { return a / b }
};
function calc(){
var n1 = parseFloat(document.getElementById("n1").value);
var n2 = parseFloat(document.getElementById("n2").value);
var oper = document.getElementById("operators").value;
const resEl = document.getElementById("result");
resEl.value = '';
const comEl = document.getElementById("Comments");
comEl.innerHTML = '';
let result;
let targetEl;
if (isNaN(n1) || isNaN(n2)) {
targetEl = comEl;
result = "Write something valid in the boxes, silly.";
}
else if (options[oper]) {
target = resEl;
result = options[oper](n1, n2);
}
else {
targetEl = comEl;
result = "Pick an operation." ;
}
let prop = typeof result === 'string' ? 'innerHTML' : 'value';
targetEl[prop] = result;
}
I am designing a page where can display score when the users make their choices.
However, this code seems not working and does not show any result in the 'score' field.
My Html code:
<tr>
<td>
<div>
<input list="typeList" name="type" id="type">
<datalist id="typeList">
<option value="basketball">
<option value="soccer">
<option value="table tenis">
</datalist>
</div>
</td>
<td><input type="text" id="score" name="score" autocomplete="off"></td>
</tr>
My Script is below:
var type = document.getElementById("type");
var score = document.getElementById("score");
if (type === 0) {
score.value = 0;
} else if (type === 'basketball') {
score.value = 1;
} else if (type === 'soccer') {
score.value = 2;
} else if (type === 'table tenis') {
score.value = 3;
}
I have used Jquery in this, The mistake you made is, there is no watch for the event.
$('#type').on('input',function(e){
var type = document.getElementById("type").value;
var score = document.getElementById("score");
if (type === 0) { score.value = 0; }
else if (type === 'basketball') { score.value = 1; }
else if (type === 'soccer') { score.value = 2; }
else if (type === 'table tenis') { score.value = 3; }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<div>
<input list="typeList" name="type" id="type">
<datalist id="typeList">
<option value="basketball">
<option value="soccer">
<option value="table tenis">
</datalist>
</div>
</td>
<td><input type="text" id="score" name="score" autocomplete="off"></td>
</tr>
Hope this helps
var type = document.getElementById("type");
//...
here should be var type = document.getElementById("type").value;
and also
if (type === 0) {
to
if (type === "0") {
You were able to access the element. You just need to use the value attribute of the element. You need to add the event change with dropdown so that it can bind the data in the score textbox when index is changed.
var type = document.getElementById("type");
var score = document.getElementById("score");
type.addEventListener('change', function() {
if (type.value === 0) {
score.value = 0;
} else if (type.value === 'basketball') {
score.value = 1;
} else if (type.value === 'soccer') {
score.value = 2;
} else if (type.value === 'table tennis') {
score.value = 3;
}
});
<tr>
<td>
<div>
<input list="typeList" name="type" id="type">
<datalist id="typeList">
<option value="basketball">
<option value="soccer">
<option value="table tennis">
</datalist>
</div>
</td>
<td><input type="text" id="score" name="score" autocomplete="off" ></td>
</tr>
You need to add a event listener (or two, one for change and one for input) and then wrap your code in a function:
var type = document.getElementById("type");
var score = document.getElementById("score");
type.addEventListener("change", function() {
myFunction(type.value);
});
type.addEventListener("input", function() {
myFunction(type.value);
});
var myFunction = function(type) {
if (type === 0) {
score.value = 0;
} else if (type === 'basketball') {
score.value = 1;
} else if (type === 'soccer') {
score.value = 2;
} else if (type === 'table tenis') {
score.value = 3;
}
}
<tr>
<td>
<div>
<input list="typeList" name="type" id="type">
<datalist id="typeList">
<option value="basketball">
<option value="soccer">
<option value="table tenis">
</datalist>
</div>
</td>
<td><input type="text" id="score" name="score" autocomplete="off"></td>
</tr>
in your if it should be
type.value
to get the value of the input box. Also when are you running the script?
// you forgot to attach the value property of the type element
var typeValue = document.getElementById("type").value;
// the result for typeValue is allways a string or undefined
var scoreElement = document.getElementById("score");
// a swtich case is more efficient here
swtich(typeValue){
case 'basketball':
scoreElement.value = 1;
break;
case 'soccer':
scoreElement.value = 2:
break;
case 'table tenis'
scoreElement.value = 3;
break;
default:
sourceElement.value = 0;
}
Here you go with pure JavaScript along with jsfiddle https://jsfiddle.net/4oyrw61w/
document.getElementById('type').addEventListener('input', function () {
var type = document.getElementById("type").value;
var score = document.getElementById("score");
if (type === '0') {
score.value = 0;
} else if (type === 'basketball') {
score.value = 1;
} else if (type === 'soccer') {
score.value = 2;
} else if (type === 'table tenis') {
score.value = 3;
}
});
So I'm creating a hybrid mobile JS app and everything is working fine so far until this last else if statement. I'm trying to convert inches to yard. I have the right code down, but its still not working. I only get the same number I type back in the results. What am I doing wrong? I am using Jquery and Jquery Mobile in the app as well.
Heres the HTML bit:
<form>
<div class="ui-field-contain">
<select name="select-native-3" id="distance" data-iconpos="left">
<option value="inch">Inch</option>
<option value="foot">Foot</option>
<option value="yard">Yard</option>
<option value="mile">Mile</option>
<option value="mm">Millimeter</option>
<option value="m">Meter</option>
<option value="km">Kilometer</option>
</select>
</div>
<h4>Convert To:</h4>
<div class="ui-field-contain">
<select name="select-native-3" id="distanceToo" data-iconpos="left">
<option value="1">Inches</option>
<option value="2">Feet</option>
<option value="3">Yards</option>
<option value="4">Miles</option>
<option value="5">Millimeters</option>
<option value="6">Meters</option>
<option value="7">Kilometers</option>
</select>
</div>
</form>
Now the JavaScript part:
$("#calcD").on("tap", function() {
var dist = document.getElementById("inpD").value;
var answerAreaD = document.getElementById("ansD");
var select = document.getElementById("distance");
var selectToo = document.getElementById("distanceToo");
if(select.value == "inch" && selectToo.value == "1") {
answerAreaD.value = dist;
}
else if(select.value == "foot" && selectToo.value == "2") {
answerAreaD.value = dist;
}
else if(select.value = "yard" && selectToo.value == "3") {
answerAreaD.value = dist;
}
else if(select.value = "mile" && selectToo.value == "4") {
answerAreaD.value = dist;
}
else if(select.value == "mm" && selectToo.value == "5") {
answerAreaD.value = dist;
}
else if(select.value == "m" && selectToo.value == "6") {
answerAreaD.value = dist;
}
else if(select.value == "km" && selectToo.value == "7") {
answerAreaD.value = dist;
}
else if(select.value == "inch" && selectToo.value == "2") {
var distInchFeet = dist / 12;
answerAreaD.value = distInchFeet;
}
else if(select.value == "inch" && selectToo.value == "3") {
var distInchYard = dist * 0.0277777777778;
answerAreaD.value = distInchYard;
}
});
In all of your else if statements you need to have the comparison operator == or ===. For mile and yard you have =, which is assigning the value rather than comparing it.
I Have a drop down list accompanied by some javascript & jquery which displays some text and a check box depending on the choice. If the checkbox is ticked then the HTML displayed will change again. Text & checkbox are being displayed however when checking the tick box html is then not changing.
HTML:
<div class="plan">
<div class="plan-details1"></div>
<div class="plan-name">
<select id="myselect">
<option value="0">Please Select Your Mobile Plan</option>
<option value="1">Package 1</option>
<option value="2">Package 2</option>
<option value="3">Package 3</option>
<option value="4">Package 4</option>
<option value="5">Package 5</option>
<option value="6">Package 6</option>
</select>
</div>
<div class="plan-price"></div>
</div>
JS
$(function () {
$('#myselect').change(function () {
var val = $(this).val();
if (val == '1') {
$('.plan-details1').html('This Is Working 1<br/>');
$('.plan-price').html('<div id="price-m">Price: €18</div><input type="checkbox" id="handset-m" value="Car" onClick="validate()"> Handset');
}
if (val == '2') {
$('.plan-details1').html('This Is Working 2<br/>');
$('.plan-price').html('<div id="price-l">Price: €25</div><input type="checkbox" id="handset-l" value="Car" onClick="validate()"> Handset');
}
if (val == '3') {
$('.plan-details1').html('This Is Working 3<br/>');
}
if (val == '4') {
$('.plan-details1').html('This Is Working 4<br/>');
}
if (val == '5') {
$('.plan-details1').html('This Is Working 5<br/>');
}
if (val == '6') {
$('.plan-details').html('This Is Working 6<br/>');
}
});
});
function validate() {
if (document.getElementById('handset-m').checked) {
document.getElementById('price-m').innerHTML = 'Price: €20';
} else {
document.getElementById('price-m').innerHTML = 'Price: €18';
}
if (document.getElementById('handset-l').checked) {
document.getElementById('price-l').innerHTML = 'Price: €35';
} else {
document.getElementById('price-l').innerHTML = 'Price: €25';
}
}
A fiddle can be found here: http://jsfiddle.net/5Y4b6/
Many thanks for your help!
This is not working because you insert the checkboxes as HTML markup. The onclick handlers is never attached to a real function. Change your code to this :
if (val == '1') {
$('.plan-details1').html('This Is Working 1<br/>');
$('.plan-price').html('<div id="price-m">Price: €18</div><input type="checkbox" id="handset-m" value="Car"> Handset');
document.getElementById("handset-m").onclick = validate;
}
if (val == '2') {
$('.plan-details1').html('This Is Working 2<br/>');
$('.plan-price').html('<div id="price-l">Price: €25</div><input type="checkbox" id="handset-l" value="Car"> Handset');
document.getElementById("handset-l").onclick = validate;
}
Now thew checkboxes is actually attached to the validate() function. BTW, change the validate function to check if the checkboxes exists / is inserted to avoid "cannot set checked of null" errors :
function validate() {
if (document.getElementById('handset-m')) {
if (document.getElementById('handset-m').checked) {
document.getElementById('price-m').innerHTML = 'Price: €20';
} else {
document.getElementById('price-m').innerHTML = 'Price: €18';
}
}
if (document.getElementById('handset-l')) {
if (document.getElementById('handset-l').checked) {
document.getElementById('price-l').innerHTML = 'Price: €35';
} else {
document.getElementById('price-l').innerHTML = 'Price: €25';
}
}
}
forked fiddle -> http://jsfiddle.net/8upk3/
Edit:
validate is actually on the global scope, but the problem is with the validate function itself:
here is a fixed version:
function validate() {
if(document.getElementById('handset-m')) {
if (document.getElementById('handset-m').checked) {
document.getElementById('price-m').innerHTML = 'Price: €20';
} else {
document.getElementById('price-m').innerHTML = 'Price: €18';
}
}
if (document.getElementById('handset-l')) {
if (document.getElementById('handset-l').checked) {
document.getElementById('price-l').innerHTML = 'Price: €35';
} else {
document.getElementById('price-l').innerHTML = 'Price: €25';
}
}
}
Scope problem.
You can either try to put listeners on your checkboxes, or declare your function in your document.ready
validate = function() {
if (document.getElementById('handset-m').checked) {
document.getElementById('price-m').innerHTML = 'Price: €20';
} else {
document.getElementById('price-m').innerHTML = 'Price: €18';
}
if (document.getElementById('handset-l').checked) {
document.getElementById('price-l').innerHTML = 'Price: €35';
} else {
document.getElementById('price-l').innerHTML = 'Price: €25';
}
};
I updated your fiddle here
Note that your function is not really efficient, you should test the presence of your elements ('handset-m', ''handset-l'...) before testing if they are checked.
EDIT
Here's an other way to do it, with jQuery listeners :
$('#plan').on('click','#handset-m, #handset-l', function(){console.log('test');
$this = $(this);
id = this.id;
var lbl = 'Price: €';
if(true === $this.prop('checked')){
lbl += ('handset-m' === id) ? '20' : '35';
}
else {
lbl += ('handset-m' === id) ? '18' : '25';
}
$this.prev('div').html(lbl);
});
fiddle here