2016-05-17 47 views
1

當第一個選擇已被更改時,以下我的功能需要更新某個行值(水果名稱)。我如何更新最後的<「input」>元素?我不知道什麼是正確的DOM屬性使用。Javascript:如何通過DOM元素進行更新?

我需要使用DOM,所以我不需要在標籤上設置ID。

HTML

<table> 
    <tbody> 
     <tr> 
      <td>Option: 
      <select onChange="updateValue(this);"> 
       <option>A</option> 
       <option>B</option> 
      </select> 
      </td> 
      <td>Quantity: 
      <select> 
       <option>1</option> 
       <option>2</option> 
      </select> 
      </td> 
      <td>Shipping Address: 
      <input type="text"/> 
      </td> 
      <td>Fruit Name: 
      <input type="text"/> 
      </td> 
     </tr> 
    </tbody> 
</table> 

的Javascript:

function updateValue(obj){ 
    var _input = obj.parentNode.nextSibling.firstChild; 
    _input.innerText = 'Apple'; 

} 
+3

沒有[input type * textbox *](http://w3c.github.io/html/sec-forms.html#sec-states-of-the-type-attribute)。 * innerText *是一個IE瀏覽器專有屬性,在所有瀏覽器中都不支持,輸入沒有任何* innerText *,它們有*值*。 – RobG

回答

0

讓你的HTML的微小變化code.Add一類,這將有助於識別要更新的輸入。使用parentNode兩次以移動至tr。然後使用className找到您要更新

<td>Fruit Name: 
      <input type="text" class="fruitClass"/> 
      </td> 

JS更改input

function updateValue(obj){ 
    var _input = obj.parentNode.parentNode.getElementsByClassName("fruitClass")[0] 
    _input.value = 'Apple'; 

} 

檢查你使用parentNode這個jsFiddle

0

https://jsfiddle.net/kavxatro/6/

function updateValue(obj){ 
    // get the last TD of this TR 
    var _input = obj.parentNode.parentNode.lastChild; 
    // make sure we are on the TD. If not, get the previous object. 
    if (typeof _input.tagName == 'undefined') _input = _input.previousSibling; 
    // get the input inside the TD 
    _input = _input.lastChild; 
    // make sure we are on the input. If not, get the previous object. 
    if (typeof _input.tagName == 'undefined') _input = _input.previousSibling; 
    // change the input value 
    _input.value = 'Apple'; 
} 

第一次您獲得SELECT的父級,即TD

第二個parentNode獲取此TD的父級,即TR

您可以使用lastChild獲取此TR中的最後一個元素,即最後一個TD

而且由於您只有一個元素在TD之內,因此firstChildlastChild應該爲您提供input對象。

要更改輸入字段的值,請使用value而不是innerText

此外,沒有HTML表單類型textbox。如果你想要一個單行輸入表格,那麼text是你應該使用的類型。

 <td>Fruit Name: 
     <input type="text"/> 
     </td> 
+0

這是拋出錯誤無法設置null的屬性'值'。查看此jsfiddle https://jsfiddle.net/kavxatro/2/ – brk

+0

確實,lastChild似乎採取了最後一個換行符。它在這裏工作https://jsfiddle.net/kavxatro/5/用'obj.parentNode.parentNode.lastChild.previousSibling.lastChild.previousSibling;'。但我不確定這是否會在每個瀏覽器中以相同的方式工作。您可能還需要進行一些檢查。 –

1

firstElementChild & lastElementChild是要得到html元素而不是文本(html字符串)。所以它是更好的獲取特定的元素!

function updateValue(obj){ 
    var _input = obj.parentNode.parentNode.lastElementChild.firstElementChild; 
    _input.value = 'Apple';  
}