2009-05-28 41 views
0

我有大約20個複選框。當用戶選擇這些,然後使用替代提交按鈕時,我需要更改所選輸入的名稱/值對的名稱。如何更改多個選定html值的名稱?

這個功能爲什麼只改變的名字隔開選中的輸入?

function sub_d() 
{ 

    for (i = 0; i < document.checks.OGname.length; i++) //for all check boxes 
    { 
     if (document.checks.OGname[i].checked == true) 
     { 
      document.checks.OGname[i].name="newname"; //change name of input 

     } 

    } 

    document.checks.submit(); 
} 

輸出:

newname 
    '105' 
OGname 
    '106' 
newname 
    '107' 
OGname 
    '108' 
newname 
    '109' 
OGname 
    '110' 
+0

我們可以看到您使用的HTML? – 2009-05-28 00:53:16

回答

1

通過重命名列表的第一個元件已減少一個列表的長度和已刪除的第一個元素。下次通過循環時,前面的第二個元素現在是第一個元素,第二個元素是舊的第三個元素。

我不是JavaScript的專家,但沿線的東西可能工作。

function sub_d() 
{ 
    i=0; 
    while (document.checks.OGname.length > i) 
    { 
    if (document.checks.OGname[i].checked="true") 
     { 
     document.checks.OGname[i].name="newname"; 
     }else{ 
     i++; 
     } 
    } 
    document.checks.submit(); 
} 

正如我所說的,沒有保修或保證。

1

如果您提供了對您的場景的更詳細的描述,但是我希望我的回答有用,那將會很棒。

​​

我通常用這種方式管理DOM集合:(我不知道,如果是最好的方式)

function sub_d() 
    {  
     var theInputs = document.checks.getElementsByTagName('input'); 
     for (var i = 0; i < theInputs.length; i++) 
     { 
      if (theInputs[i].type == 'CHECKBOX') 
       if (theInputs[i].checked) 
        { 
         theInputs[i].name="newname";   
        }  
     }  
     document.checks.submit(); 
    } 
+0

謝謝,我更改了代碼以使用getElementsByName函數,因此我不必爲下面的長度未定義問題添加額外的邏輯。 – 2009-05-28 21:44:35

0

隨着你的球員幫助我想出了這個,似乎運作良好。讓我知道,如果它可以改善他人使用...

function sub_d() 
{ 

    for (i = 0; i < document.checks.OGname.length; i++) //for all check boxes 
    { 
     if (document.checks.OGname[i].checked == true) 
     { 
      document.checks.OGname[i].name="newname"; //change name of input data so we know it is for other function 
      //By renaming the first element of the list, we have reduced the length of the list by one 
      //and deleted the first element. This is why we need to keep i at it's current position after a name change. 
      i=i-1; 
     } 
    } 

    //When there is only one check box left it's propert length becomes undefined. 
    //We will need this statement for the last undefined check box not covered in the for loop 
    //We can no longer index user[0] 
    document.checks.OGname.name="newname"; 

    document.checks.submit();//submit these checked values to the .exe 

} 
+0

我說我不知道​​JavaScript :)我沒有預料到長度變得不確定。我仍然喜歡用一段時間,而不是在循環內減少我,這似乎更清楚。你可以使用我的代碼,但改變循環條件退出長度未定義,然後捕獲最後一個?在循環中捕捉它會很高興,但我可能會有點寶貴。 – 2009-05-29 01:31:37