JQuery返回元素为null

时间:2013-12-12 15:39:07

标签: jquery html ruby-on-rails ruby-on-rails-3

Ruby on Rails 3。 我有一个div id我试图隐藏或显示基于所选复选框的值。我的脚本现在无法通过id获取元素。它返回null。我尝试了输入ID和名称。两者都返回null。

这是脚本:

$(document).ready(function() {
$('#device').change(function(event){ 
var hardware = document.getElementById('#survey_hardware_');
if (($(hardware).find("input[value='IP Phones']:checked").length) || ($(hardware).find("input[value='IP PBX Systems']:checked").length))
{
    $('#phonepbx').css('display', 'inline');
}
else
{
    $('#phonepbx').css('display', 'none');
}
});
});

这是呈现的HTML问题:

<div class="row" id="device">
<ul>1.  What IP hardware does your company frequently sell and/or install?  (select all that apply)<br/>
<li style="display:block;"><input id="survey_hardware_" name="survey[hardware][]" type="checkbox" value="IP Phones" /> IP Phones</li>
<li style="display:block;"><input id="survey_hardware_" name="survey[hardware][]" type="checkbox" value="IP PBX Systems" /> IP PBX Systems </li>
<li style="display:block;"><input id="survey_hardware_" name="survey[hardware][]" type="checkbox" value="IP Security/Surveillance Systems" /> IP Security/Surveillance Systems</li>
<li style="display:block;"><input id="survey_hardware_" name="survey[hardware][]" type="checkbox" value="IP infrastructure (cabling, switches...etc.)" /> IP infrastructure (cabling, switches...etc.)</li>
</ul>
</div>

摘要:

document.getElementById('#survey_hardware_');

返回null。我试过#survey [硬件] []和#survey [硬件] [0]并且都是空的。我如何获得元素?谢谢(请不要讨厌我的李造型:)。

解决方案

function checkHardware() {
if ($('#device input:checkbox:eq(0)').is(':checked') || $('#device input:checkbox:eq(1)').is(':checked'))
{
    $('#phonepbx').css('display', 'block');
}

等...

3 个答案:

答案 0 :(得分:2)

尝试没有'#':

document.getElementById('survey_hardware_');

或直接使用jQuery:

$('#survey_hardware_')

答案 1 :(得分:1)

你为什么要使用getElementById?你有jquery,所以使用:

$("#survey_hardware_").find(

答案 2 :(得分:0)

类似于:(注意新的和唯一的ID)

<li style="display:block;"><input id="phones" name="survey[hardware][]" type="checkbox" value="IP Phones" /> IP Phones</li>
<li style="display:block;"><input id="pbx" name="survey[hardware][]" type="checkbox" value="IP PBX Systems" /> IP PBX Systems </li>
<li style="display:block;"><input id="security" name="survey[hardware][]" type="checkbox" value="IP Security/Surveillance Systems" /> IP Security/Surveillance Systems</li>
<li style="display:block;"><input id="infra" name="survey[hardware][]" type="checkbox" value="IP infrastructure (cabling, switches...etc.)" /> IP infrastructure (cabling, switches...etc.)</li>

然后直接使用jQuery:$('#new_id_here')已经建议。