JS Turning Radio Button into algorithm param - javascript

I made a simple program that generates a random build for an NBA 2k21 MyPlayer for one of my classes. Every button the user clicks generates a random value for each trait.
I am now trying to alter the program to remember the user input for the height radio buttons and then generate a random position based on that user's selection.
I want the program to randomize between:
PG/SG if the height is between 6'2" and 6'5" or
SG/SF if the height is between 6'5" and 6'8" or
SF/PF if the height is between 6'8" and 6'10" or
PF/C if the height is between 6'10 and 6'11"
Originally the program was just 3 buttons that generates random values from an array, but now it consists of 3 buttons and a user selection of radio buttons. Here is what I had before I got stuck:
<h1>
2k Archetype Generator
</h1>
<p>
Choose Height
</p>
<form>
<input name="height" type="radio" id="h1"> 6'2"
<br>
<input name="height" type="radio" id="h2"> 6'3"
<br>
<input name="height" type="radio" id="h3"> 6'4"
<br>
<input name="height" type="radio" id="h4"> 6'5"
<br>
<input name="height" type="radio" id="h5"> 6'6"
<br>
<input name="height" type="radio" id="h6"> 6'7"
<br>
<input name="height" type="radio" id="h7"> 6'8"
<br>
<input name="height" type="radio" id="h8"> 6'9"
<br>
<input name="height" type="radio" id="h9"> 6'10"
<br>
<input name="height" type="radio" id="h10"> 6'11"
<br>
</form>
<br>
<button id="positionchoice" onclick="randpos()">
Position
</button>
<p id="pos">
</p>
<button id="primary" onclick="randprim()">
Primary
</button>
<p id="no1">
</p>
<button id="secondary" onclick="randsecond()">
Secondary
</button>
<p id="no2">
</p>
var p = document.getElementById("pos");
var skill1 = document.getElementById("no1");
var skill2 = document.getElementById("no2");
var height = ["6'2","6'3","6'4","6'5","6'6","6'7"
,"6'8","6'9","6'10","6'11"];
var primary = ["Shot Creating", "Playmaking", "Defensive"
,"Sharpshooting","3-Point","Rebounding"];
var secondary = ["Slasher", "Finisher", "Shooter",
"Ball Handler","Lockdown", "Two-Way"];
var arr = ["PG", "SG", "SF", "PF", "C"];
function randpos() {
}
function randprim() {
skill1.innerHTML = primary[Math.floor(Math.random()*primary.length)];
}
function randsecond() {
skill2.innerHTML = secondary[Math.floor(Math.random() * secondary.length)];
}

Hopefully this will help get you unstuck so that you can write the next part of your function. Here is how you can get the currently selected option:
function randpos() {
let height = document.querySelector("input[name='height']:checked").value;
height = parseInt(height);
}
<h1>
2k Archetype Generator
</h1>
<p>
Choose Height
</p>
<form>
<input name="height" type="radio" id="h1" value="74"> 6'2"
<br>
<input name="height" type="radio" id="h2" value="75"> 6'3"
<br>
<input name="height" type="radio" id="h3" value="76"> 6'4"
<br>
<input name="height" type="radio" id="h4" value="77"> 6'5"
<br>
<input name="height" type="radio" id="h5" value="78"> 6'6"
<br>
<input name="height" type="radio" id="h6" value="79"> 6'7"
<br>
<input name="height" type="radio" id="h7" value="80"> 6'8"
<br>
<input name="height" type="radio" id="h8" value="81"> 6'9"
<br>
<input name="height" type="radio" id="h9" value="82"> 6'10"
<br>
<input name="height" type="radio" id="h10" value="83"> 6'11"
<br>
</form>
<br>
<button id="positionchoice" onclick="randpos()">
Position
</button>
I have edited your <input/> elements to include a value attribute so that you can then select that directly from the JS. Additionally you may notice that these values are in inches only. You can make these values in feet and inches, like are still displayed to the user, but it is likely going to make your life easier implementing the next part of your function if you have a single number you can make comparisons with.
In the JavaScript since your button is not attached to a form you want to set up a query selector looking for any <input/> element with a name set to height. To get only the currently selected element we then look for the :checked pseudo-class selector. Finally we get the value of the element that is returned and assign it to a height variable. (Alternatively you can attach your button to the form if you give the form a name which then would allow you to process it in a more typical fashion)
Since you are likely going to want to make comparisons with this value you can then take the height variable, a string, and convert it to a number using the parseInt() function.

Related

Jquery - How do you get checkbox values from closest parent only?

I am working on a school assignment and we are starting to learn Jquery
I am looking to collect the values from a set of check boxes but only the ones that fall within the div that the button that triggers the function is contained within.
So far I have been able to get the values, but if any of the boxes are checked in the other divs those values are added as well because they need to all share the same name. I am trying to avoid duplicating code.
This is my Jquery code:
$(document).ready(function() {
$('button').on('click', function() {
var destination = $(this).closest('.destinations'); //this selects the div the button is in but I can't figure out how to apply it to the checkbox value gathering
var base_price = $(destination).find('.base_price').text();
var add_ons = [];
$.each($("input[name='add_on']:checked"), function(){ //I player around with using the variable destination somewhere here but am thinking there needs to be another step
add_ons.push($(this).val());
});
$(this).remove();
console.log(base_price)
console.dir(add_ons) //the values are successfully added but I can't figure out how to isolate based on the the variable 'destination'
});
});
HTML
<div class = "destinations">
<h2>New York, New York</h2>
<img src="images/newyork.jpeg">
<p>
Includes: 5 Night Hotel Stay, Central Park Tours, and New York Skyscrapers Package<br>
Starting at $<span class="base_price">1299.99</span>
</p>
<div>
<h3>Add-Ons</h3>
<input type="checkbox" id="option1" name="add_on" value="1000">
<label for="option1"> Add Two-Night Stay at the Ritz</label><br>
<input type="checkbox" id="option2" name="add_on" value="200">
<label for="option2"> Broadway Show</label><br>
<input type="checkbox" id="option3" name="add_on" value="400">
<label for="option3"> New York Steakhouse Gourmet Night Out</label><br>
</div>
<div>
<button id = "nyny">Get price</button>
</div>
</div>
<div class="destinations">
<h2>Paris, France</h2>
<img src="images/eiffel_tower.jpeg">
<p>
Includes: 5 Night Hotel Stay, 3 Museum Package, and Taste of France Tour<br>
Starting at $<span class="base_price">1699.99</span>
</p>
<div>
<h3>Add-Ons</h3>
<input type="checkbox" id="option1" name="add_on" value="1000">
<label for="option1"> 3 day Vineyards and Flowers Tour</label><br>
<input type="checkbox" id="option2" name="add_on" value="200">
<label for="option2"> Visit the Eiffel Tower</label><br>
<input type="checkbox" id="option3" name="add_on" value="400">
<label for="option3"> Meet President Macron</label><br>
</div>
<button id = "paris">Get Price</button>
</div>
<div class = "destinations">
<h2>Tokyo, Japan</h2>
<img src="images/tokyo.jpeg">
<p>
Includes: 5 Night Hotel Stay, Build a Pokemon Event, and a Bonsai Class<br>
Starting at $<span class="base_price">1199.99</span>
</p>
<div>
<h3>Add-Ons</h3>
<input type="checkbox" id="option1" name="add_on" value="1000">
<label for="option1"> Wagyu Steak Dinner at Aragawa</label><br>
<input type="checkbox" id="option2" name="add_on" value="200">
<label for="option2"> Random Japanese Game Show Night!</label><br>
<input type="checkbox" id="option3" name="add_on" value="400">
<label for="option3"> Mount Fuji Adventure</label><br>
</div>
<button id = "japan">Get Price</button>
</div>
Any assistance will be greatly appreciated
You should only select checkbox within that parent div.
$(document).ready(function() {
$('button').on('click', function() {
var destination = $(this).closest('.destinations'); // selecting the div container
var base_price = $(destination).find('.base_price').text();
var add_ons = [];
//$(destination) selects the parent div and find() function finds checkbox within that div.
$(destination).find("input[name='add_on']:checked")).each(function(){
add_ons.push($(this).val());
});
$(this).remove();
console.log(base_price)
console.dir(add_ons);
});
});

If statements in jquery not behaving as expected

I am relatively new to jQuery. I am trying to create a survey; in the survey each question in in its own div and is revealed by clicking the "Next" button. I just have all divs hidden except for the current div. I'm trying to write the answers to an object as I go to simplify the code. There are questions answered with radio buttons, some text areas, some check boxes, and some selects. Here is my code:
$('.next-button').click(function() {
if ($(this).parent().has('.survey-question-option')) {
replies[$(this).parent().attr('id')] = $(this).parent().contents('.survey-question-option:checked').val();
} else if ($(this).parent().has("textarea")) {
replies[$(this).parent().attr('id')] = $(this).parent().contents("textarea").val();
}
console.log(replies);
$(this).parent().attr('hidden', '');
$(this).parent().next().removeAttr('hidden');
});
I'm logging the Object (replies) to make sure things are working. As the code is currently formulated I get the answers to the first two questions (both of which are radio buttons) added to replies, but the next two objects (textareas) populate as undefined. ({reason: "bill", wish: "newstart", dislike: undefined, like: undefined}). I tried formulating the if statement as two separate statements:
if ($(this).parent().has('.survey-question-option')) {
replies[$(this).parent().attr('id')] = $(this).parent().contents('.survey-question-option:checked').val();
};
if ($(this).parent().has("textarea")) {
replies[$(this).parent().attr('id')] = $(this).parent().contents("textarea").val();
};
That returns undefined for the radio buttons, but the contents of the two textareas shows up in the object. ({reason: undefined, wish: undefined, dislike: "dislike text", like: "like text"}). In doing some testing on my own I've determined that if the if statement is formulates as if...else if the formula always applies the if statement only, but if it is created with two if statements it skips thew first and goes straight for the second.
My logic is that each Next button is in a div with the responses, so I should be able to look at the parent of the Next button, find the appropriate class, and get the value. And it seems to only work 50% of the time no matter how I formulate it.
EDIT: I am attaching the relevant html sections.
$('.next-button').click(function() {
if ($(this).parent().has('.survey-question-option')) {
replies[$(this).parent().attr('id')] = $(this).parent().contents('.survey-question-option:checked').val();
} else if ($(this).parent().has("textarea")) {
replies[$(this).parent().attr('id')] = $(this).parent().contents("textarea").val();
}
console.log(replies);
$(this).parent().attr('hidden', '');
$(this).parent().next().removeAttr('hidden');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="survey">
<div id="reason" class='radio'>
<p class="survey-question">What is the primary reason you visit the site? </p>
<input type="radio" id="bill" name="reason" class="survey-question-option" value="bill">
<label for="bill" class="survey-question-option-label">To view or pay my bill online</label><br>
<input type="radio" id="outage" name="reason" class="survey-question-option" value="outage">
<label for="outage" class="survey-question-option-label">To view or report an outage</label><br>
<input type="radio" id="start" name="reason" class="survey-question-option" value="start">
<label for="start" class="survey-question-option-label">To get information about starting or stopping services</label><br>
<input type="radio" id="hours" name="reason" class="survey-question-option" value="hours">
<label for="hours" class="survey-question-option-label">To find Frederick Waster's business hours</label><br>
<input type="radio" id="board" name="reason" class="survey-question-option" value="board">
<label for="board" class="survey-question-option-label">To get information about Frederick Water's governance or board meetings</label><br>
<input type="radio" id="devel" name="reason" class="survey-question-option" value="devel">
<label for="devel" class="survey-question-option-label">To get information about new water or wastewater lines for new development</label><br>
<input type="radio" id="other" name="reason" class="survey-question-option" value="other">
<label for="other" class="survey-question-option-label">Other</label><br>
<div id="other-fill-reason" class="other-fill" hidden>
<label for="othertext-reason" class="survey-question-option-label">Please specify: </label>
<input type="text" class="survey-question-other" id="othertext-reason">
</div>
<input type="button" class="next-button" id="reason-next" value="Next">
</div>
<div id="wish" class='radio' hidden>
<p class="survey-question">What do you wish the site did better?</p>
<input type="radio" id="newstart" name="wish" class="survey-question-option" value="newstart">
<label for="newstart" class="survey-question-option-label">Allow me to pay deposit while starting new service</label><br>
<input type="radio" id="outinfo" name="wish" class="survey-question-option" value="outinfo">
<label for="outinfo" class="survey-question-option-label">Provide easier-to-find information about outages</label><br>
<input type="radio" id="startstop" name="wish" class="survey-question-option" value="startstop">
<label for="startstop" class="survey-question-option-label">Make it easier to start and stop services</label><br>
<input type="radio" id="request" name="wish" class="survey-question-option" value="request">
<label for="request" class="survey-question-option-label">Make it easier to request maintenance for existing service</label><br>
<input type="radio" id="chat" name="wish" class="survey-question-option" value="chat">
<label for="chat" class="survey-question-option-label">Let me talk to customer service online</label><br>
<input type="radio" id="other2" name="wish" class="survey-question-option" value="other">
<label for="other2" class="survey-question-option-label">Other</label><br>
<div id="other-fill-wish" class="other-fill" hidden>
<label for="othertext-wish" class="survey-question-option-label">Please specify: </label>
<input type="text" class="survey-question-other" id="othertext-wish">
</div>
<input type="button" class="next-button" id="wish-next" value="Next">
</div>
<div id="dislike" class="textbox" hidden>
<p class="survey-question">What do you dislike about the site?</p>
<textarea id="dislike-text" class="like-dislike" cols="100" rows="5" maxlength="500" wrap="soft"></textarea><br>
<input type="button" class="next-button" id="dislike-next" value="Next">
</div>
<div id="like" class="textbox" hidden>
<p class="survey-question">What do you like about the site?</p>
<textarea id="like-text" class="like-dislike" cols="100" rows="5" maxlength="500" wrap="soft"></textarea><br>
<input type="button" class="next-button" id="like-next" value="Next">
</div>
has() doesn't return a boolean, it returns a jQuery object. Objects are always truthy.
If you want to test whether a selector finds anything, test the length of the result.
$('.next-button').click(function() {
if ($(this).parent().find('.survey-question-option').length > 0) {
replies[$(this).parent().attr('id')] = $(this).parent().find('.survey-question-option:checked').val();
} else if ($(this).parent().find("textarea").length > 0) {
replies[$(this).parent().attr('id')] = $(this).parent().find("textarea").val();
}
console.log(replies);
$(this).parent().attr('hidden', '');
$(this).parent().next().removeAttr('hidden');
});

populate 'today + x days' as form input value [duplicate]

I am trying to use the innerHTML method on an input tag and all i get back is a blank string. Here is the code i am useing.
javascript
function setName(ID){
document.getElementById('searchtitle').innerHTML = "Enter " + ID.innerHTML;
}
HTML
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)">Last Name</input><br/>
<input type="radio" name="searchtype" value="phonenumber" onclick="setName(this)">Phone Number</input><br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label><br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;"></input>
What is supposed to happen is depending on which radio button I pick the label for the input box should change. I can make the label.innerHTML=radio.value but the values are named for my php code and not formated nicely(ie. phonenumber vs. Phone Number) this is why I am trying to use the innerHTML of the radio button.
Any help I could get would be greatly appriciated.
you should embed input inside of label tag. input tag should closed by />. It's semantic HTML. When you do this clicking on label activate the input. InnerHTML only works for label then. It will return you label value.
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;" />
</label>
JavaScript:
console.log(document.getElementById('searchtitle').innerHTML); // returns 'Enter Last Name'
If you want the value of an input tag, you want to use .value.
First, add labels around your inputs. Second, use getName(this.parentNode). Finally, call innerText instead of innerHtml.
<html>
<head>
<script>
function setName(el){
document.getElementById('searchtitle').innerHTML = "Enter " + el.innerText;
}
</script>
</head>
<body>
<label><input type="radio" name="searchtype" value="name" onclick="setName(this.parentNode)"/>Last
Name</label><br/>
<label><input type="radio" name="searchtype" value="phonenumber" onclick="setName(this.parentNode)"/>Phone
Number</label><br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label><br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;"></input>
</body>
</html>
Complete edit.
Ok, I figured out what you were looking for. First off, you've got to fix your HTML (don't put text inside of an input... and don't next an input inside of a label).
<label for="test">Last Name</label>
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)" />
<br/>
<label for="test2">Phone Number</label>
<input type="radio" id="test2" name="searchtype" value="phonenumber" onclick="setName(this)" />
<br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label>
<br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;" />
JavaScript (in Jquery, for brevity):
function setName(elem)
{
$('#searchtitle').html('Enter ' + $('label[for="'+elem.id+'"]').html());
}
You have closed the Input tag improperly with </input>
this should be
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)"/>Last Name<br/>
<input type="radio" name="searchtype" value="phonenumber" onclick="setName(this)"/>Phone Number<br/>

how to get only one radio button value in javascript

<input type="radio" name="red" value ="red" onclick="myFunction(this.value);"id="chkbx" /> Red<br>
<input type="radio" name="green" value ="green" onclick="myFunction(this.value);"id="chkbx" > green<br>
<input type="radio" name="yellow" value ="yellow " checked onclick="myFunction(this.value);"id="chkbx" > yellow<br>
<input type="radio" name="orange" value ="orange" onclick="myFunction(this.value);"id="chkbx" > orange<br>
<input type="radio" name="blue" value ="blue" onclick="myFunction(this.value);"id="chkbx" > blue<br>
<p id="demo"></p>
button onclick="myfunction(this.value)">My Choice</button>
<br><br>
<p id="demo"></p>
<script>
function myFunction(chkbx)
{
if(chkbx.checked)
{
chkbx.checked = false;
}
else
{
chkbx.checked = true;
}
The Thing is " I want to get the colour from radio button apply to a text in output screen(at a time one radio button would be select).What can i do. Please give some idea. i am new to javascript. I want in javascript only.
.Value will return you the value:
function myFunction(chkbx)
{
if(chkbx.checked)
{
alert(chkbx.value);
}
}
Give all the radio buttons in the group the same name.
Radio buttons allow the user to select only ONE of a predefined set of options. You define groups with the name property (radio buttons with the same name belong to the same group).
So to solve your issue, you can do as belows.
<p><input type="radio" name="color" value ="red"><i>Red</i></p>
<p><input type="radio" name="color" value ="green"><i>Green</i></p>
<p><input type="radio" name="color" value ="yellow" checked><i>Yellow</i></p>
<p><input type="radio" name="color" value ="orange"><i>Orange</i></p>
<p><input type="radio" name="color" value ="blue"><i>Blue</i></p>

Javascript calling in variables from HTML Form

I have the javascript portion working (cut off bottom portion of it to reduce code length) when I manually put in the numbers however, I'm struggling with putting my javascript together with my html. I tried stealing bits of code to get it to work, ultimately I'd like to just have one button that says "Get Pricing" that passes the 4 variables quantity, colors, logoSheet, and margin to the respective javascript variables.
<form>
<br>
<label id="_quantity" >Quantity</label>
<input type="number" id="quantity" maxlength="254" data-hint="" name="quantity" required/>
<br>
<label id="_colors" ># of Colors</label>
<input type="number" id="colors" maxlength="254" data-hint="" name="colors" required/>
<br>
<label id="_logoSheet" ># Logo's per Sheet</label>
<input type="number" id="logoSheet" maxlength="254" data-hint="" name="logoSheet" required/>
<br>
<label id="_margin" >Margin %</label>
<input type="number" id="margin" maxlength="254" data-hint="" name="margin" required/>
<br>
<input type="submit" class="fb-button-special" id="fb-submit-button" value="submit" />
</form>
<button onclick="myFunction()">Get Pricing</button>
<p>Total Shirt Only:</p> <p id="totalShirtOnly"></p>
<p>Total Sheet Cost:</p> <p id="totalSheetCost"></p>
<p>Price Per Sheet:</p> <p id="costOfSheets"></p>
<p>Total Price:</p> <p id="totalPrice"></p>
<p>Net Profit:</p> <p id="netProfit"></p>
</center>
<script>
function myFunction()
{
var quantity = document.getElementById('quantity.value');
var colors = document.getElementById('colors.value');
var logoSheet = document.getElementById('logoSheet.value');
var margin = document.getElementById('margin.value');
var shirtCost = 2.43;
var sheetShipping = 15.0;
var marginPercent = margin/100;
var totalCost = 0.0;
var costOfSheets = 0.0;
</script>
</body>
</html>
I don't know which JavaScript variables you're referring to and if you're using jQuery or not but here's how to get values of HTML elements:
// With jQuery
var colors = $("#colors").val();
// w/o jQuery
var margin = document.getElementById("margin").value
Is this what you were looking for?

Categories