简体   繁体   English

根据选择选项的值更改输入的值

[英]Changing value of an input based on value of select option

When inserting data into my table, I need to insert the day of the week as well as the number of the day of the week so they can be displayed in chronological order. 将数据插入表中时,我需要插入星期几以及星期几,以便可以按时间顺序显示它们。 To remove any room for error, I want the number of the day of the week to be determined by a select option. 为了消除错误的余地,我希望通过选择选项确定星期几。

Example would be: If select option val for .day* = Mon, .daynum* = 1 例如: If select option val for .day* = Mon, .daynum* = 1

Here is what I have so far: 这是我到目前为止的内容:

HTML: HTML:

<select required class="form-control day<?php echo $i; ?>" name="day<?php echo $i; ?>" />

   <option  disabled value="">Day of the Week</option>
   <option value="Mon">Monday</option>
   <option value="Tue">Tuesday</option>
   <option value="Wed">Wednesday</option>
   <option value="Thu">Thursday</option>
   <option value="Fri">Friday</option>
   <option value="Sat">Saturday</option>
   <option value="Sun">Sunday</option>

</select>

<input required class="form-control daynum<?php echo $i; ?>" type="text" name="daynum<?php echo $i; ?>" />

jQ: JQ:

$(document).ready(function(){
$('.daynum1').val($('.day1 option:selected').val());

$('.day').on('change', function() {
    $('.daynum1').val($(this).find('option:selected').val());
});

});

Currently my code just gets the initial value of the first row pulled from the database and sets it to Monday. 目前,我的代码只是获取从数据库中提取的第一行的初始值,并将其设置为Monday。

The code I have calls all rows and lets me edit them all at once, which gives each input/select a class that is "dayx" where x is the unique id from the database. 我拥有的代码调用所有行,然后让我一次编辑所有行,这为每个输入/选择提供了一个“ dayx”类,其中x是数据库中的唯一ID。

Use this to get value from input 使用它从输入中获取价值

$(document).ready(function(){
  $('.daynum1').val();

  $('.day').on('change', function() {
    $('.daynum1').val();
  });

  });

Create an array with the day names, and use the index as the day number. 创建一个带有日期名称的数组,并将索引用作日期编号。

$(document).ready(function() {
    var days = ["", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
    $('.day').on('change', function() {
        $('.daynum1').val(days.indexOf($(this).val()));
    }).trigger("change");
});

BTW, you don't need to use option:selected to get the value of a <select> . 顺便说一句,您不需要使用option:selected来获取<select>的值。 Calling .val() on the <select> itself works. <select>本身上调用.val()起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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