简体   繁体   English

在Javascript / Jquery中提取字符串部分

[英]Extract string part in Javascript / Jquery

I'm using cocoon gem to add dynamic nested forms for the working hours. 我正在使用茧形宝石在工作时间内添加动态嵌套表格。

The Cocoon returns an open_time and close_time input. 茧返回open_time和close_time输入。

id = merchant_working_hours_attributes_ID_open_time
id = merchant_working_hours_attributes_ID_close_time

At the css the close_time input is defined as display:none and my idea is just display if the open_time input is marked not nil. 在CSS上,close_time输入定义为display:none,而我的想法只是在open_time输入标记为nil的情况下显示。

But for that I need extract the ID from the open_time input and add a css style to the close_time input according that ID. 但是为此,我需要从open_time输入中提取ID并根据该ID将css样式添加到close_time输入中。

How can achieve that with javascript / Jquery? 如何使用javascript / Jquery实现呢? Any other form to achieve that? 还有其他形式可以实现吗?

Your question says that you've a string and you wanna extract the ID of respective element to perform style. 您的问题是说您有一个字符串,并且想要提取各个元素的ID以执行样式。

Use split() 使用split()

var string = merchant_working_hours_attributes_ID_open_time;

var parts = string.split("_"); //You will have the ID at 4th parts[4]

Based on the extracted ID, you can use show() and hide() . 根据提取的ID,可以使用show()hide()

Example

if($('#opentimeID').val() != '')
{
  $('#opentimeID').show();
}

Use substring() 使用substring()

string.substring(start,end)

This should be relatively simple. 这应该相对简单。 My assumption is that, by default, the "close time" field isn't showing. 我的假设是,默认情况下,“关闭时间”字段未显示。 But, when you start to put a value into the "open time" field, the "close time" field then shows up. 但是,当您开始在“开放时间”字段中输入值时,“关闭时间”字段就会显示出来。

If that's the case, this should work for you. 如果是这样,这应该为您工作。

JavaScript 的JavaScript

const openTime = document.getElementById('merchant_working_hours_attributes_ID_open_time')
const closeTime = document.getElementById('merchant_working_hours_attributes_ID_close_time')
if (openTime.value.length > 0) {
  closeTime.style.display = 'block'
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM