2017-05-03 77 views
0

無法訪問輸入的checked屬性

<input type="checkbox" onclick="price_change('<?=$service_new_price;?>',this.id)" <?php echo $checked ?> value="<?php echo $entityId; ?>" id="service-option-<?php echo $entityId; ?>" class="service-option" name="service-option[]">

其顯示其他一切的時候,我就複選框點擊我應該心存感激,如果有人幫我

function price_change(value, id) { 
 
    var x = document.getElementsByClassName('price')[0].innerHTML; 
 
    var n_price = x.replace(/[^\w\s.]/gi, '') 
 

 
    if (id.checked) { 
 
    var new_price = +n_price + +value; 
 
    console.log('checked'); 
 
    } else { 
 
    var new_price = +n_price - +value; 
 
    console.log(id, 'uncheck'); 
 
    } 
 
    //document.getElementsByClassName('price')[0].innerHTML = new_price; 
 
    //document.getElementsByClassName('price')[1].innerHTML = new_price; 
 
}

+0

是什麼控制檯說? – binariedMe

+2

當你調試這個時,'id.checked'的價值是什麼?什麼是傳遞給這個函數的'id'? – David

+0

看起來不像你正在評估(id.checked)的任何東西。 – Stese

回答

2

您將輸入的id作爲字符串傳遞給您的函數,但您正在處理它li關注輸入對象。相反,經過id的,傳遞對象本身:

onclick="price_change('<?=$service_new_price;?>',this)" 

然後你就可以點到對象的屬性:

function price_change(value, obj) { 
    var x = document.getElementsByClassName('price')[0].innerHTML; 
    var n_price = x.replace(/[^\w\s.]/gi, '') 

    if (obj.checked) { 
    var new_price = +n_price + +value; 
    console.log('checked'); 
    } else { 
    var new_price = +n_price - +value; 
    console.log(id, 'uncheck'); 
    } 
} 

編輯 爲了解決關於能夠看到價值的評論id在控制檯中:

您可以在控制檯中看到id的值,因爲它存在 - 作爲一個字符串。你不能說<string>.checked,因爲字符串沒有一個名爲checked的屬性 - 只有你的輸入對象。

簡單地說,傳遞對象,或基於您傳入的id(我更喜歡前者)來檢索對象。

+0

但我在控制檯中獲取id,但只是如果條件不起作用我點擊時獲取id –

+0

您在控制檯中獲取'id',因爲它存在 - **作爲字符串**。你不能說' .checked'因爲字符串沒有一個名爲checked的屬性。 –

+0

謝謝你的工作 –

-1

這可能有助於

const priceChange = (value, id) => { 
 
\t // You need to get the element, not just use its ID 
 
    const checkbox = document.querySelector('#'+id); 
 
    if(checkbox.checked){ 
 
    \t // Change price 
 
    console.log(checkbox.checked); 
 
    } 
 
    else{ 
 
    \t // do something else 
 
    console.log(checkbox.checked); 
 
    } 
 
}
<label><input type='checkbox' id='myCheckbox' onclick='priceChange(10, this.id)' /> Checkbox</label>

+0

爲什麼downvote?它不能幫助解決問題嗎? – sesamechicken