数组将字符串放置在索引[0]中

时间:2018-12-26 02:23:57

标签: javascript php

我是javascript新手。当前尝试将选项选择中的多个值输入到数组中并将其提取到表单中。

我尝试了数组和对象方法,但结果返回了 x [0] 的整个字符串,但没有为 x [1] x [ 2]

grammar so;

program: ( statement EOL )* EOF ;

statement:
    address_stmt |
    data_stmt |
    ;

address_stmt: ADDRESS_KWD (DECIMAL_NUMBER | HEX_NUMBER) ;
data_stmt: DATA_KWD VALUE (',' VALUE)* ;

ADDRESS_KWD: [aA][dD][dD][rR][eE][sS][sS] ;
DATA_KWD : [dD][aA][tT][aA] ;

VALUE: DECIMAL_NUMBER | HEX_NUMBER | BINARY_NUMBER | STRING ;
DECIMAL_NUMBER: [0-9]+ ;
HEX_NUMBER: '$' [0-9a-fA-F]+ ;
BINARY_NUMBER: '%' [01]+ ;
STRING: '"' [^"]+ '"' ; // very basic string definition
/* VALUE: DECIMAL_NUMBER | HEX_NUMBER | BINARY_NUMBER | STRING ; */

WHITESPACE: [ \t]+ -> skip;
EOL: '\r'? '\n';

Js函数

// Select Option
Customer: <?php echo "<select name='customer' id='customer' 
onchange='updateValue2(this);'>";

while ($rows = mysqli_fetch_assoc($results)) { ?>
<option value="'<?php echo $rows['pic']; ?>','<?php  echo 
$rows['contact'];?>','<?php echo $rows['address']; ?>'"><?php echo 
$rows['Name']; ?>
</option>

//Display return value in this textboxes
PIC: <input type="text" id="pic" name="pic">
<br><br>

Contact: <input type="text" id="contact" name="contact">
<br><br>

X [0] 返回'Robert','12345678','worths street'
  x [1] x [2] 返回未定义

2 个答案:

答案 0 :(得分:0)

select元素中检索所选选项的方式不正确。您必须首先从value属性中获取字符串,然后将其转换为数组,例如:

function updateValue2(e)
{
    var selectedOption = e.options[e.selectedIndex].value;
    var x = selectedOption.split(',');

    if (x.constructor === Array) {
        document.getElementById('pic').value = x[0];
    } else {
        document.getElementById('pic').value = Not_Array;
    }
    document.getElementById('contact').value = x[1];
    document.getElementById('address').value = x[2];
}
Customer:
<select name='customer' id='customer'onchange='updateValue2(this);'>
<option value=",,"></option>
<option value="'pic1','contact1','adress1'">Name1</option>
<option value="'pic2','contact2','adress2'">Name2</option>
<option value="'pic3','contact3','adress3'">Name3</option>
<option value="'pic4','contact4','adress4'">Name4</option>
</select>

<br><br>

PIC: <input type="text" id="pic" name="pic">

<br><br>

Contact: <input type="text" id="contact" name="contact">

<br><br>

Address: <input type="text" id="address" name="address">

答案 1 :(得分:0)

您的HTML渲染是否正确?

我不知道它是否有用,但是您应该检查下拉菜单的循环和渲染过程,当下拉“选择”末尾等时会造成混淆...

我修改了循环,请看一下。

  // Select Option
  Customer: <select name='customer' id='customer' onchange='updateValue2(this);'> 

  <?php 
  while ($rows = mysqli_fetch_assoc($results)) { 

    echo '<option value=" '.$rows['pic'].','.$rows['contact'].','.$rows['address'].' "> 
    '.$rows['Name'].' </option> ';

   } ?>

   </select>

   //Display return value in this textboxes
   PIC: <input type="text" id="pic" name="pic">
   <br><br>

   Contact: <input type="text" id="contact" name="contact">
   <br><br>