Reputation: 1
Let's say I have a select with some option values
<select name="select">
<option value="item-one">Item one</option>
<option value="item-two">Item two</option>
</select>
<input type="number" name="quantity">
If I selected Item one, I want the input number to have a max allowed value of 3, otherwise if Item two if selected it would be 4.
I tried looping it using foreach loop but wont return the right result
Upvotes: 0
Views: 136
Reputation: 853
Php works on the server-side so you cant do that unless you send a command to the server. Its much easier to do in javascript.
Its not a good approach, but you can do something like this, to give you an idea, you can make an ajax request to the php side with javascript's onselect function. You will make a validator function on the php side and you will retrieve the data sent from onselect. After the validations, example you sent "Item One" , php validator will return you 3. At the success method of javascript, you will take the returned data and set it to the input type as the max value with javascript again.
If there is complicated calculations that you want to make at the behind rather than this 3,4 this could be a way you are looking for. But if you just need 3,4 or simple things like that, just go with the javascipt.
Upvotes: 0
Reputation: 177786
You cannot do that in PHP but with JavaScript you can.
I use an array where the index matches the selectedIndex of the select
I trigger on load and I also reduce if the select is changed
I added an input event handler too, because min/max only works with the spinners AND the submit event.
Alternative for my input test is to set and trigger custom validity on the input field
window.addEventListener("DOMContentLoaded", () => {
const sel = document.querySelector("[name=select]");
const numberField = document.querySelector("[name=quantity]");
sel.addEventListener("change", (e) => {
numberField.max = [3,4][e.target.selectedIndex];
if (+numberField.value > +numberField.max) numberField.value = numberField.max;
});
sel.dispatchEvent(new Event('change')); // initial value
numberField.addEventListener("input",(e) => {
const val = numberField.value;
if (+val > +numberField.max) numberField.value = numberField.max;
})
numberField.addEventListener("blur",(e) => {
const val = numberField.value;
if (isNaN(parseFloat(val)) || !isFinite(val)) numberField.value = 0; // field allows [e.-+] remove on blur if no digits
})
});
<select name="select">
<option value="item-one">Item one</option>
<option value="item-two">Item two</option>
</select>
<input type="number" name="quantity">
Upvotes: 1