简体   繁体   English

在将选项文本分配给隐藏输入时,如何从选择选项中删除HTML nbsp标记

[英]How can i remove HTML nbsp tags from select options when assigning the text of option to hidden input

When the value is assigned to html hidden element it also assign nbsp tag which is in select statement. 将值分配给html hidden元素时,它还会分配nbsp标记,该标记位于select语句中。 I don't want any html tags just only text 我不希望任何html标签只是文本

 function setTextFieldA(ddl) { var a = ddl.options[ddl.selectedIndex].text; var res = a.slice(0,12); alert(res); document.getElementById('prod1').value = res; /*document.getElementById('prod1').value = ddl.options[ddl.selectedIndex].text;*/ } 
 <select name="1" id="1" class="selectadd" onchange="setTextFieldA(this)" required > <option value="99">Red Vein </option> <option value="99">White Vein </option> <option value="99">Green Vein </option> <option value="109">Red Horned &nbsp; [Add $10]</option> <option value="109">White Horned [Add $10]</option> <option value="109">Green Horned [Add $10]</option> <option value="109">Maeng da &nbsp; &nbsp; &nbsp; [Add $10]</option> </select> <input id="prod1" type = "hidden" name = "prod1" value = "Red Vein" /> 

First, do not use slice, you never know what length your value may be. 首先,不要使用切片,你永远不知道你的价值可能是多长。 Remove var res = a.slice(0,12); 删除var res = a.slice(0,12);

Second, you can use regular expression to remove all white spaces and the price tag at the end of the string, like this: 其次,您可以使用正则表达式删除字符串末尾的所有空格和价格标签,如下所示:

var res = res.replace(/\s*(\[.*\])*$/, ""); //removes white spaces and "[Add 10$]" tag

If you use jQuery: 如果你使用jQuery:

function setTextFieldA(ddl) {
  var res = $('option:selected',ddl).text().slice(0,12).trim();
  alert(res);
  $('#prod1').val(res);
}

Check this Fiddle 检查这个小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从文本中删除html标签并将其存储在EL中? - How can i remove html tags from a text and store it in EL? 如何获取标题属性包含“”的输入标签? - How can I get input tags with title attributes that contain "&nbsp;"? 如何在 select 和选项 html 标签上添加和删除自定义错误注释 class? - How can I add and remove custom error note class on select and option html tags? 当我有五个具有相同选项和值的select时,如何从另一个select标记中删除一个选中的选项? - How to remove a selected option from another select tag when i have five select with same options and values? 如何使用 jQuery 从字符串中删除输入标签? 该字符串还包含其他 html 标签 - How can I remove input tags from a string using jQuery? This string contains other html tags as well "选择选择选项时如何显示隐藏的 div?" - How can I show a hidden div when a select option is selected? 删除表格 HTML 上的标签 - Remove tags &nbsp; on Table HTML 使用select2插件添加或删除项目时如何更改隐藏的输入值 - How can I change hidden input val when add or remove item with using select2 plugin 选择一个选项后,我想更改其他 select 标签选项 - When an option selected I wanna change the other select tags options 如何删除元素中的内容? - How can I remove content like &nbsp; from an element?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM