The script is for a gambling game. User types in wager and number from 2,3,5,50.
If the wheel spins , and the number on the wheel equals to the number , the user gets wager * number.
Example: User wagers 100 credits and bets on 2. Wheel spins and if it lands on 2 , User Gets 100*2 credits.
How do I change from typing 2,3,5,50 into a input, to a button "bet on 2" , " bet on 3 " , respectively.
Problem with my current: User enters every round as long as a valid wager and number is provided, when the wheel spins. Using a button, will allow the user to choose when he wants to bet( which is by clicking the button)
Check this out: http://codepen.io/hokaien/pen/RKjPbZ
if ( options[index] === wantTo ) {
// if options[index] equals to number
var el = document.getElementById('number');
var res = originalNumber += (amountBet * wantTo);
el.textContent = res;
finalMsg = " You won " + (amountBet * wantTo) + " credits";
} else if (test3 != "2" || test3 != "3" || test3 != "5" || test3 != "50") {
finalMsg = " Number should be from 2, 3, 5, 50 ";
} else if (amountBet > originalNumber) {
finalMsg = " Not enough credits ";
} else if (amountBet < 0) {
finalMsg = " Cannot bet negative ";
}
Here you go (codepen)
HTML added:
<input type='button' class='betButton' value="2"/>
<input type='button' class='betButton' value="3"/>
<input type='button' class='betButton' value="5"/>
<input type='button' class='betButton' value="50"/>
also removed the number input
JS added (jQuery):
this code handles clicks and sets the value of currentBet, it also adds a class called selected to the player's choice for clarity
$('.betButton').click(function() {
currentBet = $(this).val();
$(this).addClass("selected");
$('.betButton').not(this).removeClass("selected");
});
JS Edits:
replaced refrences to the old number input and replaced it with currrentBet... afected variables are: wantTo, test2 and test3
replaced the code that used to disable/enable input while spinning with
$( ".betButton" ).prop( "disabled", true )
and
$( ".betButton" ).prop( "disabled", false )
to disable and enable the bet buttons instead
CSS added:
input.betButton {
border: none;
background: white;
color: black;
border-radius: 5px;
padding-left: 10px;
padding-right: 10px;
cursor: pointer;
}
input.betButton:disabled {
opacity: 0.4;
}
input.betButton.selected {
background: red;
color: white;
transition: 0.5s;
}
Example
$(function() {
$('#btn').click(function() {
var data = $(this).val();
if(isNaN(data) == false)
{
alert('this is numeric');
}
else
{
alert('Not a numbre');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="button" id="btn" value="2" >
You can get the text of the buttons
Suppose you have four buttons
<input type='button' class='myButton' value="2" />
<input type='button' class='myButton' value="3" />
<input type='button' class='myButton' value="5" />
<input type='button' class='myButton' value="50" />
You can easily check if the value is number or not
$('input.myButton').click(function(){
var btn = $(this)
var btnValue = btn.val();
var isNum = $.isNumeric(btnValue);
});
If your button is defined as <button type="button">[num]</button Then you can get btn.text() in place of btn.val().
If using jQuery, you can use .isNumeric() to check for an input whether its number or not.
var result=$.isNumeric(txtInput.val());
Check for clicked buttons value
var result=$.isNumeric(btnClickedButton.val());
Or
$(".btnNumber2").click(function(){
var result=$.isNumeric($(this).val());
alert(result);
});
UPDATED ANSWER
HTML
<input type='button' class='myButton' value="bet on 2" data-val="2" />
<input type='button' class='myButton' value="bet on 3" data-val="3" />
<input type='button' class='myButton' value="bet on 5" data-val="5" />
<input type='button' class='myButton' value="bet on 50" data-val="50" />
JS
var clickedScore=0;
$(".myButton").click(function(){
var btn=$(this);
clickedScore=btn.attr("data-val");
});
function CheckIfClickedButtonValueEqualsWheelNumber() //HAVE TO MAKE IT LONG
{
if(parseInt(clickedScore)==YOUR_NUMBER_FROM_WHEEL){
{
//YOUR EXISTING LOGIC, NOT REPEATING IT HERE
}
}
Related
I'm creating a quiz that contains 10 questions: 5 multiple choice through radio input and 5 written answers through text input. See code for both inputs below. But I would also like to add a score system to these questions. I found a nice script here on stack overflow that can keep the score while user enters form input. I will add it below.
The script I use to check answers from radio input:
$(document).ready(function(){
$('input[name=radio1]').change(function(){
$('.alert').remove();
if($('input[name=radio1]:checked').val() === "1") {
$(this).parent().append('<span class="correct">✓ Correct!</span>');
} else {
$(this).parent().append('<span class="incorrect">✗ Correct answer = B</span>');
}
});
});
The correct anser given is based on value="1". The other answers have value="0".
The script I use to check answers from text input:
$('submit').on('click', function() {
markAnswers(1)
});
var answers = {
q1: ["Auto's"]
};
function markAnswers(id) {
$(`#q${id}`).each(function () {
let userAnswer = this.value.replace(/[^\w\'\,\-\?\!\"\:\—\;]/g,'');
if ($.inArray(userAnswer, answers[this.id]) === -1) {
$(this).parent().append(`<br><span class='incorrect'>✗ Correct answer = ${answers[this.id]}</span>`);
} else {
$(this).parent().append("<br><span class='correct'>✓ Correct!</span>");
}
});
}
The correct value from text input is determined by this script above.
Now, the script I found that keeps the score, collects score through data-score=. But I was thinking to just use value instead. See original script below:
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var score = 0
$('input.track').each(function(){
var _score = $(this).data("score")
if ($(this).val().length > 0) {
score += _score
}
})
$('#score').text(score)
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
The script can be found here: https://stackoverflow.com/a/58297288/4546157
It is really nice. It keeps the score but it also shows you if you have completed the form or not.
I would like each correct answer to have a value of 1 so at the end of the quiz the user can have a maximum score of 10/10. But, a big but, I don't know how to implement it. Hoping to see suggestions or solutions from you guys. Thank you!
You would do it something like this. Though it's bad practice to use globally available variables, but for the sake of simplicity i put them there. Better to wrap everything in a div and store score/progress as data attributes.
Pen: https://codepen.io/lenadax/pen/QWQqMxP?editors=1111
// global vars, put them somewhere else
var progress = 0;
var score = 0;
$('form.question').each(function(i, el) {
// I'm lazy so form id is the same as input name for each question
let inputs = $(`input[name=${$(this).attr('id')}]`);
inputs.on('change', function() {
// increase progress by 1 if button has been selected.
progress++;
if ($(this).val() === "1") {
// increase score if correct choice selected
score++;
$('<span class="result correct">').text('✓ Correct!').appendTo(el);
} else {
$('<span class="result incorrect">').text('X Incorrect!').appendTo(el);
}
// get number of questions
let question_count = $('form.question').length;
// disable after choosing for less hassle
inputs.prop('disabled', true);
// calculate the progress in percent
let progress_num = progress / question_count * 100;
$('.perc').text(progress_num);
$('#score').text(`${score} / ${question_count}`);
});
})
input {
display: inline-block;
}
label {
display: inline-block;
}
button {
display: block;
}
form {
width: 200px;
border: 1px solid gray;
margin: 10px;
padding:10px 5px;
}
.result {
display: block;
}
.result.incorrect {
color: red;
}
.result.correct {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form class="question" id="question1">
<span>Question 1</span>
</p>
<input name="question1" id="answer1" type="radio" value="0"/>
<label for="answer1">Wrong answer</label>
</p>
<input name="question1" id="answer2" type="radio" value="1"/>
<label for="answer2">Right answer</label>
</form>
<form class="question" id="question2">
<span>Question 2</span>
</p>
<input name="question2" id="answer1" type="radio" value="0"/>
<label for="answer1">Wrong answer</label>
</p>
<input name="question2" id="answer2" type="radio" value="0"/>
<label for="answer2">Wrong answer</label>
</p>
<input name="question2" id="answer3" type="radio" value="1"/>
<label for="answer3">Right answer</label>
</form>
<h5>Done <span class='perc'>0</span>%</h5>
<h5>Score <span id="score">0</span></h5>
</body>
</html>
Here is my code, can somebody just tell me how to turn these into buttons which I can click instead of options, that would be really helpful.
Thank You
function check() {
//All Variables
var num = parseInt(document.getElementById("n1").value);
var oper = document.getElementById("operator").value;
//If Statements
if (oper === "Sqaure") {
document.getElementById("result").innerHTML = "The square root of " + num + " is " + Math.sqrt(num);
}
if (oper === "Cube") {
document.getElementById("result").innerHTML = "The cube root of " + num + " is " + Math.cbrt(num);
}
}
body {
user-select: none;
}
#btn1 {
cursor: pointer;
}
Number: <input type="text" placeholder="Enter Number" id="n1" /><br>
<select id="operator">
<option value="Sqaure">Square Root</option>
<option value="Cube">Cube Root</option>
</select>
<input type="button" value="Find" onclick="check();" id="btn1" /><br><br>
<p id="result"></p>
Remove the select field and add in a second (button) input field.
The onclick attribute of both buttons can pass the desired operation to the check function.
Inside the check function, everything remains the same -- except there is no need to retrieve the operator, since its now an argument to the function.
Consider the following live snippet which achieves the above. It also uses isNan() to check if the entered data is a valid number -- and if not, display an error message instead.
function check(operation) {
const num = parseInt(document.getElementById("n1").value);
if (isNaN(num)) {
document.getElementById("result").innerHTML = 'Please enter a number';
} else {
let root;
if (operation === "square") {
root = Math.sqrt(num);
} else if (operation === "cube") {
root = Math.cbrt(num);
}
document.getElementById("result").innerHTML = `The ${operation} root of ${num} is ${root}`;
}
}
body {
user-select: none;
}
#btn1 {
cursor: pointer;
}
Number:
<input type="text" placeholder="Enter Number" id="n1">
<p>
<input type="button" value="Square Root" onclick="check('square');" id="btn1">
<input type="button" value="Cube Root" onclick="check('cube');" id="btn2">
</p>
<p id="result"></p>
I have more than 23 buttons on my page and they can be decreased or increased.
how can i count all buttons and create progress bar according to status change of button. There are only two status one will increase percentage and another will decrease.
Click here to see the image of the buttons and progress bar that i created
Here is my code
$(document).ready(function() {
var form_count = 1;
setProgressBar(form_count);
function setProgressBar(curStep) {
var i = 0;
$.each($('input[type=submit]'), function() {
if ($(this).val() == 'Revisit') {
i++;
}
});
var total = i * 4;
var percent = total;
percent = Math.floor(percent);
if (percent > 100) {
percent = 100;
}
$(".progress-bar")
.css("width", percent + "%")
.html(percent + "%");
}
});
This code work fine, but i need it dynamically.
Here is HTML code for all buttons i do same code
<div class="col-md-6">
<div class="frmWrp">
<form method="post" action="">
<div class="heading">Quality Assurance</div>
<div class="btn pull-right">
<?php if ($feature_enable[0]['qa_mod'] == 1) { ?>
<input type="submit" class="btn btn-default" name="user_configration1" value="<?php echo ($checkExist[0]['quality_assurance'] == 1) ? 'Revisit' : 'Visit'; ?>">
<?php } else { ?>
<button class="btn btn-default" disabled>Feature Not Enabled</button>
<?php } ?>
</div>
</form>
</div>
</div>
For example now i have 25 buttons and i do var total = i * 4; for getting 100%, if buttons are less than i have to change 4 manually. but i need this dynamically.
Any solution appreciated!
Here is a general idea of how to use an eventListener to update the width property of a div's style attribute when a user clicks a "Submit" or "Revisit" button:
// Identifies the progress bar
const progressBar = document.getElementsByClassName("progressBar")[0];
// Calls the `setProgressBar` function when the user clicks something
document.addEventListener("click", setProgressBar);
// Defines the `setProgressBar` function
function setProgressBar(event) {
// Makes sure the click was on an `input` element with the `submit` type before proceeding
if(
event.target.tagName == "INPUT" &&
event.target.getAttribute("type") == "submit"
){
// Toggles the value of the clicked input element
if(event.target.value == "Revisit"){ event.target.value = "Submit"; }
else{ event.target.value = "Revisit"; }
// Bascially the same as your original code -- updates the progressBar
let i = 0;
$.each($('input[type=submit]'), function() {
if ($(this).val() == 'Revisit') { i++; }
});
const percent = Math.min(i * 25, 100);
$(".progressBar").css("width", percent + "%").html(percent + "%");
}
}
#container{ width: 10ch; }
input[type=submit]{ margin-bottom: 0.2em; }
.progressBar{ height: 20px; background-color: yellow; width: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<input type="submit" value="Submit" />
<input type="submit" value="Submit" />
<input type="submit" value="Submit" />
<input type="submit" value="Submit" />
</div>
<div class = "progressBar"></div>
I have below options, I want to use 1,2,3 options as radio button.
[checkbox] option 1 : $100
[checkbox] option 2 : $200
[checkbox] option 3 : $300
[checkbox] Registration fee : $50
Total = Option + Registration fee;
After selecting check box, value should be added into total and after unchecking, value should be deductefromtotal`. but the challenge is I want to use option 1,2 and 3 as radio buttons (only one option should be selected one time). But if I am using standard radio buttons for options then value is including in total on select but not deducting old options value from total if i select new option.
I used this code
<script type="text/javascript">
var total = 0;
function fee(item) {
if (item.checked) {
total += parseInt(item.value);
} else {
total -= parseInt(item.value);
}
// alert(total);
document.getElementById('Totalcost').innerHTML = total + "";
}
</script>
HTML
<input id="checkbox1" type="checkbox" name="program1" value="100" onClick="fee(this);"/>
<input id="checkbox2" type="checkbox" name="program2" value="200" onClick="fee(this);"/>
<input id="checkbox3" type="checkbox" name="program3" value="300" onClick="fee(this);"/>
<input id="checkbox4" type="checkbox" name="fee" value="50" onClick="fee(this);"/>
I assume you need at least one of them.
Radios will uncheck if they have the same name:
function calc() {
var rads = document.getElementsByName("option"),
reg = document.getElementById("reg"),
total = document.getElementById("total"),
tot = 0;
for (var i=0;i<rads.length;i++) {
tot+=rads[i].checked?parseInt(rads[i].value,10):0;
}
if (reg.checked) tot += parseInt(reg.value,10);
total.value=tot;
}
window.onload=function() {
var rads = document.getElementsByName("option"),
reg = document.getElementById("reg");
for (var i=0;i<rads.length;i++) {
rads[i].onclick=calc;
}
reg.onclick=calc;
}
<input type="radio" name="option" id="option1" value="100" />100
<input type="radio" name="option" id="option2" value="200" />200
<input type="radio" name="option" id="option3" value="300" />300 <br/>
<input type="checkbox" name="reg" id="reg" value="50" />50<br/>
Total <input type="text" readonly id="total" /><br/>
The name and concept of "radio button" comes from the old car radios where pressing one button would make the other button reset:
I don't want to discuss about how your design is probably wrong.
But I like to introduce a solution that does not imply some javascript to disable all checkbox and only allow one to be selected.
By changing the style of a radio button to look like a checkbox, you can easily achieve what you are asking.
form > input[type="radio"] {
-webkit-appearance: checkbox;
-moz-appearance: checkbox;
appearance: checkbox;
}
<form>
<input type="radio" name="program" value="100" /> program1<br />
<input type="radio" name="program" value="200" /> program2<br />
<input type="radio" name="program" value="300" /> program3<br />
<input type="checkbox" name="fee" value="50" /> fee
</form>
You SHOULD not use this and think of using some radio button. This is counter intuitive for users.
try this:
function fee(ev) {
var total = 0;
var item = ev.target;
if (item.checked) {
total += parseInt(item.value);
} else {
total -= parseInt(item.value);
}
// alert(total);
document.getElementById('Totalcost').innerHTML = total;
}
document.querySelector('form').addEventListener('change', fee);
<div id='Totalcost'>0000</div>
<form>
<input type="radio" name='name' value="100">option1(100£)
<br>
<input type="radio" name='name' value="200">option2(200£)
<br>
</form>
using form and change event the code is more concise
Personally I would use a simple MVVM library for this, Vue.js is a rather simple example.
This way you don't have to use your DOM as a datastore and both your presentation and your logic are separated rather clearly.
var v = new Vue({
el: 'body',
data: {
checkboxes: [{
name: 'first',
value: 100,
checked: false
}, {
name: 'second',
value: 200,
checked: false
}, {
name: 'third',
value: 300,
checked: false
}],
optional: {
name: 'optional',
value: 50,
checked: false
}
},
methods: {
foo: function() {
var sum = this.checkboxes.reduce(function(sum, item) {
return sum + (item.checked ? item.value : 0);
}, 0);
sum += this.optional.checked ? this.optional.value : 0;
return sum;
},
bar: function(e) {
if (e.targetVM.checked) {
this.checkboxes.forEach(function(checkbox) {
checkbox.checked = false;
});
e.targetVM.checked = true;
}
}
}
});
ul {
list-style: none;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.12/vue.min.js"></script>
<ul>
<li v-repeat="checkboxes">
<input type="checkbox" id="checkbox_{{name}}" v-model="checked" v-on="click: bar" />
<label for="checkbox_{{name}}">{{name}}: {{value}}</label>
</li>
</ul>
<input type="checkbox" v-model="optional.checked" id="optional_{{optional.name}}" />
<label for="optional_{{optional.name}}">{{optional.name}}</label>
<p>Total: <span v-text="foo()"></span>
</p>
I think this is pretty straight forward.
$(".total").html("$" + (parseInt($(this).val()) + 500));
Made a small fiddle for you here.
Try something like below, would require a lot of clean up.
$(document).ready(function() {
//set initial state.
var fee= 50;
$('#val1').change(function() {
if($(this).is(":checked")) {
var returnVal = $('#val1').val();
alert(returnVal);
fee = parseInt(fee) + parseInt(returnVal);
alert(fee);
} else {
alert('unchecked');
var returnVal = $('#val3').val();
alert(returnVal);
fee = parseInt(fee) - parseInt(returnVal);
alert(fee);
}
});
$('#val2').change(function() {
if($(this).is(":checked")) {
var returnVal = $('#val2').val();
alert(returnVal);
fee = parseInt(fee) + parseInt(returnVal);
alert(fee);
} else {
alert('unchecked');
var returnVal = $('#val2').val();
alert(returnVal);
fee = parseInt(fee) - parseInt(returnVal);
alert(fee);
}
});
$('#val3').change(function() {
if($(this).is(":checked")) {
var returnVal = $('#val3').val();
alert(returnVal);
fee = parseInt(fee) + parseInt(returnVal);
alert(fee);
} else {
alert('unchecked');
var returnVal = $('#val3').val();
alert(returnVal);
fee = parseInt(fee) - parseInt(returnVal);
alert(fee);
}
});
});
I have two checkboxes in a group and one text input. If one (or both) of the checkboxes are selected I need to have the text input be required, as well as if the text input has text I need at least one of the checkboxes to be required. Another problem I'm having it that it's using a custom templating engine (PHP backend) and is a pain to configure and get the attributes correct, another issue is it's all referenced by the name attribute and this is why I'm using a HTML5 data-group for the checkbox options which I think it working.
Any help in getting this to work, combining functions (if this makes it easier/simpler).
BTW it's running 1.3.2 jQuery
Example: (not working)
http://jsfiddle.net/NYn8e/1/
Any suggestions?
JS:
function checkboxSelectedRequiredAdditionalFields(elem) {
var passedElement = $('input:checkbox[name=' + elem + ']');
passedElement.click(function() {
$('input[name=number]').attr('required', true).append('<span class="required">*</span>');
alert('text is required now?');
});
}
function numberEnteredRequiredAdditionalFields(elem) {
var passedElement = $('input[name=' + elem + ']');
if (passedElement.val().length > 0) {
var boxes = $('input[data-group=cbOptions]').click(function() {
boxes.not(this).attr('required', false);
alert('checkbox is selected so other checkbox is not required');
});
$('input[data-group=cbOptions]').each(function() {
$(this).attr('required', true).next().append('<span class="required">*</span>');
alert('checkbox is required now?');
});
}
}
HTML
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox1');" data-group="cbOptions">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox2');" data-group="cbOptions">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" onclick="numberEnteredRequiredAdditionalFields('number');">
</b>
</form>
You should separate the JavaScript from the HTML. Fiddle: http://jsfiddle.net/NYn8e/6/. If possible, remove <b> from the HTML source, and extend the style sheet with the right CSS property: font-weight: bold;.
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" data-required="checkbox">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" data-required="checkbox">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" data-required="number">
</b>
</form>
JavaScript:
function required(){
//Any checked checkbox? checked == 0 = no, otherwise: yes
var checked = $('input[data-required=checkbox]:checked').length;
var $checkboxes = $('input[data-required=checkbox]');
var $num = $('input[name=number]');
var length = $num.val().length;
//Remove previously added span, if existent.
$num.next('span.required').remove();
$checkboxes.next('span.required').remove();
if(!length && checked){
$num.after('<span class="required">*</span>');
alert("Number required!");
} else if(length && !checked){
$checkboxes.after('<span class="required">*</span>');
alert("Check at least one checkbox.");
}
}
$(document).ready(function(){
$("[data-required]").change(required);
});
=) Would this one help you?
<form id='myForm'>
<input type='checkbox' name='checkbox1' value='t' id='checkbox1' onchange='alertUser()' />
<input type='checkbox' name='checkbox2' value='t' id='checkbox2' onchange='alertUser()' />
<input type='text' name='number' id='number' onchange='alertUser()'/>
</form>
<script type='text/javascrip>
function alertUser() {
var checked1 = $('#checkbox1').attr('checked');
var checked2 = $('#checkbox2').attr('checked');
var number = $('#number').val();
if ((checked1 == true || checked2 == true) && number == '') {
alert('Number is required!');
} else if (number != '' && (checked1 != true && checked2 != true)) {
alert('One of the checkbox need to be checked!');
}
});
</script>
This should hopefully give you an idea on how to accomplish the task. http://jsfiddle.net/NYn8e/8/
var $textbox = $('input[name=number]').hide();
$('input[type=checkbox]').change(function() {
var $this = $(this); //store jquery object
//get the other checkbox
var $other= ($this.attr('name') === 'checkbox1') ? $('input[name=checkbox2]') : $('input[name=checkbox1]');
if (!$other.is(':checked') && !$this.is(':checked')) {
$textbox.val('').hide();
} else{
$textbox.show();
}
});