JavaScript Regex pull out only a number in an element - javascript

How would one go about pulling out just a number in the text of an element? I want to set this as a variable.
ie. If I wanted to have a variable made from option val 171 of the number 12 so I can do calculations with it (I just want to be left with the number 12):
<select id="coloroption">
<option value="172">Granite Gray</option>
<option value="174">Hot Red</option>
<option value="173">Navy</option>
<option value="171">Kentucky Green (min. 12)</option>
</select>

var number = $('#coloroption option[value="171"]').text().match(/\d+/);
Live demo. Depending on the possible values of this option and what you need to extract from it, the regex might need tweaking.

Darin Dimitrov is the exact answer to your question. +1
However, I'm going to suggest a different approach all together, if you have control over your markup. And that's to use data- attributes to explicitly store the information that you want to use, rather than trying to use possibly fragile string parsing to get the data.
<option value="171" data-processing-minutes="12">Kentucky Green (min. 12)</option>
And then retrieve that attribute with
var value = $('#coloroption option[value="171"]').data("processing-minutes");
or
var value = $('#coloroption option[value="171"]').attr("data-processing-minutes");
Though the former is preferred.

Related

How to get the value of a drop down menu in html using js

My ultimate goal is to add the decimal value associated with the drop down item selected to any other number the user inputs (so they might input 1 and then choose 1/8 and I want it to spit out 1.125.) - it's a web app for me to keep track of the food and spices I have in the kitchen.
I can't get it to grab the value I've assigned to each option in the drop down. I keep getting the following error:
script.js:7 Uncaught TypeError: Cannot read properties of null (reading 'value')
I figured it would struggle with actual fractions, so my html drop down looks like this:
<label for="fractions"></label>
<select name="fractions" id="fractions">
<option value="0">.0</option>
<option value="0.125">1/8</option>
<option value="0.25">1/4</option>
<option value="0.67">1/3</option>
<option value="0.50">1/2</option>
<option value="0.75">3/4</option>
</select>
Originally, I had my script using var fractions = document.getElementById("fractions") and then using fractions.value to get the value I assigned in the drop down, but it wouldn't give me the value. I found pretty much the same answer on here and on another website - use .value - and I can't figure out any other way to do it.
I also tried using var whatever = parseFloat(fractions); and then whatever.value to change the value to a float and then get that value, thinking maybe it was giving me a string, so that's why it wasn't adding properly, but it had the same error on it.
I did end up changing my selector thinking maybe that was the issue, so now my script looks like this:
const fractions = document.querySelector('#fractions')
const fractionsValue = fractions.value
I also tried implement .value this way:
const fractionsValue = fractions.options[fractions.selectedIndex].value
But I keep getting the same error.
I'm probably making a really silly mistake - what am I doing wrong?
According to the error message your querySelector or getElementById is not finding the element. I tested all your attempts and they all worked for me (except the parse one). Are you sure the error is not from the other input?
Edit: see the snippet:
const fractions = document.querySelector('#fractions');
const fractions1 = document.getElementById("fractions");
console.log(fractions.value);
console.log(fractions1.value);
console.log(fractions.options[fractions.selectedIndex].value);
<label for="fractions"></label>
<select name="fractions" id="fractions">
<option value="0">.0</option>
<option value="0.125">1/8</option>
<option selected value="0.25">1/4</option>
<option value="0.67">1/3</option>
<option value="0.50">1/2</option>
<option value="0.75">3/4</option>
</select>
I have tried, and can confirm that the following code definitely works.
const fractions = document.querySelector('#fractions')
const fractionsValue = fractions.value
console.log("fractions.value:", fractionsValue)
Maybe you try to see whether the code was put in another iframe or similar issue so that it cannot find the element. Or, this code is rendered conditionally, and it even did not get rendered. Please check these pre-conditions.

How do I replace an HTML element on click?

I am developing this code for a storytelling type game and I need to change the dropbox options after the user or player is done selecting their option. I am trying to make the options in the dropbox relevant to what is happening in the game at the given moment. I was told to do research on a possible change of element(with different options in the dropbox) every time the user has chosen their option.
I have tried some jquery, but only moved the dropbox on click. I could not find any type of operator that could help me with changing it. The append bit in my code is submitting the input and getting an outcome
<div id="actions">
<select id="chosen_action">
<option value="You have entered the dungeon...">Yes</option>
<option value="You turned and left THE END">No</option>
<option value="You attempted to communicate with the enemy...">Talk</option>
</select>
<button onclick="append_to_history()">Go!</button>
</div>
You can do this really easily with .innerHTML:
$("#chosen_action").innerHTML = `
<option>You turn away from the castle</option>
<option>You take a closer look at the old drawbridge</option>
<option>You decide to consult your map</option>
`;
.innerHTML simply changes the HTML content of a given element. The backtick operators (`) form a template string, which is capable of spanning multiple lines, making it easier to lay out your new options. You could use a regular string here instead if you'd like (and of course can generate this value with a loop, array, etc).
const choice = document.getElementById('chosen_action');
const opt1 = document.getElementById('option1');
const opt2 = document.getElementById('option2');
const opt3 = document.getElementById('option3');
const go = document.getElementById('goButton');
go.addEventListener('click',(e) => {
if(choice.value !== ""){
if(choice.value === opt1.value){
opt1.value = ... //change the value of this element
opt2.value = ...
opt3.value = ...
//if need to change value of text shown to user for selection you can:
opt1.textContent = ...//change the text of this element
opt2.textContent = ...
opt3.textContent = ...
} else if(choice.value === opt2.value){
...
...
...
} else{
...
...
...
}
} else {
alert("You must make a choice to continue!")
}
})
<div id="actions">
<select id="chosen_action">
<option id="option1" value="You have entered the dungeon...">Yes</option>
<option id="option2" value="You turned and left THE END">No</option>
<option id="option3" value="You attempted to communicate with the enemy...">Talk</option>
</select>
<button id="goButton" onclick="append_to_history()">Go!</button>
</div>
I can't comment to gather more information, so, without knowing more about what you are asking, or where your game is going, or what "append_to_history()" does, or how many possible combinations there are, etc., this is one way of doing what you need to do.
In the end, I would guess you will have to make a giant object, or a great deal of smaller objects, and come up with a naming system that you can programmatically grab the proper values from when it comes time. Probably a tracker to count the number of choices (each button click) and then name your objects accordingly, so that you can use the tracker value and the option number to call the correct value. You will have to figure out, at some point, every single possible value and then programmatically call them for each new value depending on the value chosen at time of click.
Would be interested to know if anyone else has any different perspective on this, though!

Using a ONE WORD javascript variable in form field VALUES

I have a function that gets values from a the URL and then posts it to various places on the page.
I can't figure out how to get the values to read inside form field values.
<OPTION Value="<script type="text/javascript">document.write(Position)
</script> has final say">
I know I can't do that specifically, but I've tried various configurations and nothing posts the variable inside the value field.
The document.write function is working on the plain html, I have tested that. I just don't know to make it read inside a form field value and display the results properly.
How do I get one word to display as a variable, without having to create a function that inputs the value of each field. There are way too many fields to make that viable - this needs to populate into maybe 200 or 300 variables, so I really need it to be the word.
The site is standalone so I can't use php as I understand it. If there's a way I'm open to it. I did try the php echo to call the field name but I don't know enough about php to know if I'm missing something.
I am open to solutions where I can upload files into the standalone site though.
Thanks in advance.
Is this what you're looking for?
var position = 'helloworld'
document.getElementById('id1').options[0].value=position;
<select id="id1">
<option>The Value is the POSITION variable.</option>
</select>
I added an ID to the select box (<select id="id1">). Then you can use the script to insert the position variable as the value of the options within the select.
If this is not what you're looking for then you really need to update your question with more sample from your code (i.e some HTML would be nice).
If you are stuck writing code only on the client-side, then you may want to use a client-side library like jQuery to help you manage your DOM manipulation.
For example, you can set a class for every variable you want to set and then use jQuery to replace the contents of those elements.
var values = {
position: "top",
name: "steve"
}
$(".position").text(values.position).val(values.position)
$(".name").text(values.name).val(values.name)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option class="position"></option>
<option class="name"></option>
</select>
<select>
<option class="name"></option>
</select>
<select>
<option class="position"></option>
</select>
<select>
<option class="position"></option>
<option class="name"></option>
<option class="position"></option>
<option class="name"></option>
</select>

Validating select element based on pattern with AngularJS

I'm developing an Angular app and I have a form set up which I need to run validation on. One of the form elements is a <select>, like this:
<select name="noOfPeople" ng-model="noOfPeople">
<option>No of people*</option>
<option ng-repeat="amt in [] | range:12">{{ amt +1 }}</option>
</select>
Because the design doesn't allow for labels on form elements, the label is essentially the first option in the select element. I want this control to be invalid unless it matches the following pattern: /^[0-9]$/.
I have tried using ng-pattern on the <select> however that doesn't seem to have any effect, Angular always thinks the control is valid.
The only other way I can think of doing it is writing a function in my controller to check if this control is valid and block the form from submitting if it's not. But I don't want to introduce a random validation function into my nice clean controller.
What's the best way to deal with this?
You can use the ng-options attribute here, rather than ng-repeat, and attribute a blank value to any options you wish to ignore. For example:
<select name="noOfPeople" ng-model="noOfPeople" ng-options="value for value in [] | range:12">
<option value="">No of people*</option>
<option value="">This won't count either!</option>
</select>
<p>Selected Value: {{noOfPeople}}<p>
If you explicitly require the regex checking to occur, you could write a filter and add it to the ng-options.

Inserting select box text into database

I know this has been asked before, however I cannot find a solution to my problem.
I have a select box with three options and three values, these values are used to perform some calculations using JS so I cannot change these to match the option text. This is to work out the amount of V.A.T.
My select looks like this:
<select name="tax" id="tax" class="select">
<option value="20">Standard 20%</option>
<option value="0">Zero 0%</option>
<option value="0">Exempt 0%</option>
</select>
Which is fine, however I need to insert the text into the database and not the values, as it needs to be viewed in the backend. I have tried a javascript function to add a hidden input to the select box targeting the option that is selected but that was a bit buggy, and didn't seem right. i was thinking of displaying the text next to the value when it is retrieved from the database, however I wouldn't be able to distinguish from the two 0 amounts.
Could someone please offer some further solutions, best approaches to this.
Many Thanks
You can get the text of the selected option with jQuery as follows:
$("#tax option:selected").text();
You could easily use this within your AJAX request to send the correct value to the database, just assign it to a variable:
var the_text = $("#tax option:selected").text();
Failing that, why not just do the lookup in the JS calculations - it'd make your life so much easier:
<select name="tax" id="tax" class="select">
<option value="standard">Standard 20%</option>
<option value="zero">Zero 0%</option>
<option value="exempt">Exempt 0%</option>
</select>
And your JS could look something like this:
var vat_amount = ($('#tax').val() == 'standard') ? 20 : 0;
You can retrieve the text by JS using the html() function. Or, if you are just using a POST to send the data to the server, try adding both values to the value attribute of the option and split it server side to get the right data.

Categories

Resources