简体   繁体   中英

Displaying specific text after selecting from two different inputs with javascript

I have 2 different select fields one with size (eg. 10 , 20 , 30 ) and the other one with color ( red , green , yellow ). For size and color , depending on what is selected, I have different prices such as 10, red price is 200EUR, 20 green price is 300EUR etc.

Now I need to know how can I do this with JavaScript so after I've selected the size and color inputs bellow to show me the price.

Can you give me an example of an JavaScript mapping or something like that?

 <select id="size" name="size">
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
 </select> 

 <select id="color" name="color">
     <option value="red">red</option>
     <option value="green">green</option>
     <option value="yellow">yellow</option>
 </select> 

You can do something like this, using an object which holds all values corresponding to color and size

 var data = { green: { 10: '100Euro', 20: '200Euro', 30: '300Euro' }, red: { 10: '400Euro', 20: '500Euro', 30: '600Euro' }, yellow: { 10: '150Euro', 20: '250Euro', 30: '370Euro' } } // bind change event handler to listen change event $('#color,#size').change(function() { // getting value from data object based on selected value and updating div text $('#res').text(data[$('#color').val()][$('#size').val()]); })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id="size"> <option value=10>10</option> <option value=20>20</option> <option value=30>30</option> </select> <select id="color"> <option value=red>red</option> <option value=green>green</option> <option value=yellow>yellow</option> </select> <div id=res></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM