2015-03-02 3 views
0

Я делаю форму с опциями в них. Пользователь может выбрать как можно больше. Мой код находится здесь:Очистить ввод, когда флажок снят флажок

<b>Options</b> 
<br> 
<font size="1"> Please select all options wanted</font> 
<br> 
<input type="checkbox" id="none" value="X"  onchange="updateText('none')">None 
<br> 
<input type="checkbox" id="prof" value="P" onchange="updateText('prof')">Profiled w/ Data 
<br> 
<input type="checkbox" id="slave" value="SL" onchange="updateText('slave')">Slaved each end 
<br> 
<input type="checkbox" id="silco" value="SN" onchange="updateText('silco')">SilcoNert® Coating 
<br> 
<input type="checkbox" id="pass" value="PP" onchange="updateText('pass')">Power Pass Through 
<br> 
<input type="checkbox" id="dur" value="DR" onchange="updateText('dur')">Dursan Coating 
<br> 
<input type="checkbox" id="thermo" value="TP" onchange="updateText('thermo')">Thermocouple Pass Through 
<br> 
<input type="checkbox" id="ss" value="SR" onchange="updateText('ss')">Stainless Steel 1/16" Braided Strain Relief 
<br> 
<br> 
<input type="hidden" value="" maxlength="1" size="1" id="profText" /> 
<input type="hidden" value="" maxlength="1" size="1" id="slaveText" /> 
<input type="hidden" value="" maxlength="1" size="1" id="silcoText" /> 
<input type="hidden" value="" maxlength="1" size="1" id="passText" /> 
<input type="hidden" value="" maxlength="1" size="1" id="durText" /> 
<input type="hidden" value="" maxlength="1" size="1" id="thermoText" /> 
<input type="hidden" value="" maxlength="1" size="1" id="options2Text" /> 
<input type="text" value="" maxlength="1" size="1" id="completeText" style="width: 200px; border:1px solid #CC0000;" /> 

< script type = "text/javascript" > 

function updateText(type) { 
    var id = type + 'Text'; 
    var endValue; 
    var inputValue = document.getElementById(type).value; 

    document.getElementById(id).value = inputValue; 

    endValue = document.getElementById("seriesText").value; 
    if (document.getElementById("tubeText").value != "") { 
     endValue = endValue + "-" + document.getElementById("tubeText").value; 
    } 
    if (document.getElementById("sizeText").value != "") { 
     endValue = endValue + "-" + document.getElementById("sizeText").value; 
    } 
    if (document.getElementById("voltageText").value != "") { 
     endValue = endValue + "-" + document.getElementById("voltageText").value; 
    } 
    if (document.getElementById("sensorText").value != "") { 
     endValue = endValue + "-" + document.getElementById("sensorText").value; 
    } 
    if (document.getElementById("temperatureText").value != "") { 
     endValue = endValue + "-" + document.getElementById("temperatureText").value; 
    } 
    if (document.getElementById("sleeveText").value != "") { 
     endValue = endValue + "-" + document.getElementById("sleeveText").value; 
    } 
    if (document.getElementById("portText").value != "") { 
     endValue = endValue + "-" + document.getElementById("portText").value; 
    } 
    if (document.getElementById("connectorText").value != "") { 
     endValue = endValue + "-" + document.getElementById("connectorText").value; 
    } 
    if (document.getElementById("lengthText").value != "") { 
     endValue = endValue + "-" + document.getElementById("lengthText").value; 
    } 
    if (document.getElementById("profText").value != "") { 
     endValue = endValue + "-" + document.getElementById("profText").value; 
    } 
    if (document.getElementById("slaveText").value != "") { 
     endValue = endValue + "-" + document.getElementById("slaveText").value; 
    } 
    if (document.getElementById("silcoText").value != "") { 
     endValue = endValue + "-" + document.getElementById("silcoText").value; 
    } 
    if (document.getElementById("passText").value != "") { 
     endValue = endValue + "-" + document.getElementById("passText").value; 
    } 
    if (document.getElementById("durText").value != "") { 
     endValue = endValue + "-" + document.getElementById("durText").value; 
    } 
    if (document.getElementById("thermoText").value != "") { 
     endValue = endValue + "-" + document.getElementById("thermoText").value; 
    } 
    if (document.getElementById("options2Text").value != "") { 
     endValue = endValue + "-" + document.getElementById("options2Text").value; 
    } 
    document.getElementById("completeText").value = endValue; 
} < /script> 
</body > < /div> 
</div > < /div> 
</div > <br> 

Когда пользователь выбирает опцию, значение опции должно появиться в поле ввода в нижней части. Однако в настоящее время значение остается в поле ввода, когда пользователь выбирает параметр, даже если они снимают флажок. Есть ли способ очистить это значение, если флажок установлен с отметки, чтобы снять флажок с помощью javascript?

Я несколько новичок в Javascript/HTML, и я искал в Google. Результаты, похоже, не работают для моего кода.

+1

Этот сценарий уверен, не очень сухой, и почему у вас есть элементы DIV после тело закрыто? – adeneo

+0

^DRY означает «Не повторяйте себя». –

+0

Кроме того, где элементы, ни один из ID в javascript фактически не соответствует любому в HTML? – adeneo

ответ

0

Я вижу, вы включили JQuery как тег, так что у меня работает, но любитель JQuery решение для вас , Я немного изменил ваш html, особенно максимальная длина и размер были удалены из текстового поля.

<b>Options</b> 
<br> 
<font size="1"> Please select all options wanted</font> 
<br> 
<input type="checkbox" id="none" value="X">None 
<br>Profiled w/ Data 
<br> 
<input type="checkbox" id="slave" class="choice" value="SL">Slaved each end 
<br> 
<input type="checkbox" id="silco" class="choice" value="SN">SilcoNert® Coating 
<br> 
<input type="checkbox" id="pass" class="choice" value="PP">Power Pass Through 
<br> 
<input type="checkbox" id="dur" class="choice" value="DR">Dursan Coating 
<br> 
<input type="checkbox" id="thermo" class="choice" value="TP">Thermocouple Pass Through 
<br> 
<input type="checkbox" id="ss" class="choice" value="SR">Stainless Steel 1/16" Braided Strain Relief 
<br> 
<br> 
<input type="text" id="choiceDisplay" value="" id="completeText" style="width: 200px; border:1px solid #CC0000;" readOnly/> 


var $choiceDisplay = $("#choiceDisplay"), //jquery selector for the display box 
    $none = $("#none"), //jquery selector for clear-choices option 
    $choice = $(".choice"); //jquery selector for choices to list 

$choice.on("change", function() { 
    var $this = $(this), //jquery selector for the changed input 
     isThisChecked = $this.prop("checked"), //true if the box is checked 
     choiceSelectionsArray = $choiceDisplay.val().split(",").filter(function(e){return e !== ""}), //array of values that are checked 
     isThisValueInDisplayedSelection = $.inArray($this.val(), choiceSelectionsArray) !== -1; //true when $this value displayed 

    if (isThisChecked) { 
     if (isThisValueInDisplayedSelection) { 
      return false; //odd, the value is already displayed. No work to do. 
     } else { //value not in selection, so add it 
      choiceSelectionsArray.push($this.val()); 
      $choiceDisplay.val(choiceSelectionsArray.join()); 
     } 
    } else { //box has been unchecked 
     if (isThisValueInDisplayedSelection) { 
      choiceSelectionsArray = choiceSelectionsArray.filter(function(e){return e !== $this.val()}) 
      $choiceDisplay.val(choiceSelectionsArray.join()); 
     } 
    } 
}); 

$none.on("change", function() { 
    var $this = $(this), 
     isThisChecked = $this.prop("checked"); 
    if(isThisChecked){ 
     $choice.prop({ 
      disabled: true, 
      checked : false 
     }); 
     $choiceDisplay.val(""); 
    }else{ 
     $choice.prop({disabled: false}); 
     return false; 
    } 
}); 

jsFiddle

+0

Спасибо за помощь! Это работает отлично! Есть ли способ изменить «,» между вариантами «-» на всем протяжении? Я очень ценю помощь! – FlexMarket

+0

.join ("-") http://www.w3schools.com/jsref/jsref_join.asp и затем .split ("-") http://www.w3schools.com/jsref/jsref_split.asp –

0

Вы должны проверить, проверяется ли флажок и установите или снимите входной сигнал в случае необходимости:

function updateText(type) { 
    var id = type + 'Text'; 
    var checkbox = document.getElementById(type); 
    var endValue; 

    document.getElementById(id).value = checkbox.checked ? checkbox.value : ''; 
+0

эта функция должна быть привязана к событию 'onchange', чтобы работать как ожидалось –

Смежные вопросы