asp.net使用jquery和javascript来确定与按钮匹配的文本框ID的中间部分

asp.net using jquery and javascript to determine middle part of ID of textbox that matches button

本文关键字:文本 中间部 ID 按钮 jquery 使用 net javascript asp      更新时间:2023-09-26

我有一个按钮,其中它是遗留的应用程序在asp.net webforms,所以这些生成的id是我必须与工作:

<input type="button" onclick="setDateTimeOn(this);" name="GridView1:_ctl2:AddButton0" value="On" id="GridView1__ctl2_AddButton0" class="btn-blue">

<input name="GridView1:_ctl2:txtStormTimeOn" type="text" id="GridView1__ctl2_txtStormTimeOn">

我有一个函数叫做

function setDateTimeOn(x){
    //alert(x.id);   
    console.log(x.id);
    //$('#x.id').val(
    //NEED TO SET textbox to date and time in this format --> 09-11-2015 10:03
}

我需要使用jquery或javascript找到"ctl2"因此真正解析找到字符之前"_ctl2_AddButton0"和之后"GridView1__"

有一些代码,我在过去使用jquery与regex中,我会使用"^"和部分名称,但在这种情况下,我知道格式总是

 GridView1__VALUEIWANT_txtStormTimeOn

然后我知道如何填充我的文本框与该值(有许多行所有gridview预生成与asp.net web表单,我不能改变它在这个应用程序。

编辑/更新

到目前为止,这更接近

function setDateTimeOn(x){

console.log(x.id);   // shows GridView1__ctl2_AddButton0

var re = /__(.+)_/; 
// your control name was used an as example:
//var str = 'GridView1__ctl2_AddButton0';
var str = x.id;
var m;
if ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
}
// View your result using the m-variable.
// m[0] == 'ctl2'
    console.log(m[0]);  // shows __ctl2_

}

编辑2:

  <table>
      <tr>
        <td style="width:5px;">
        <input type="button" name="GridView1:_ctl2:AddButton0" value="On" id="GridView1__ctl2_AddButton0" class="btn-blue">
       </td>
        <td style="width:150px;">
        <input name="GridView1:_ctl2:txtStormTimeOn" type="text" value="asdfasdf" id="GridView1__ctl2_txtStormTimeOn">
       </td>
    </tr>
</table>

试试这个

function setDateTimeOn(elm) {
    var formattedDate = GetCurrentDateTime(); //get formatted date
    $(elm) //clicked button
        .parent("td") // container td
        .next() // next td
        .find("input") // find child input
        .val(formattedDate); //set date
}
function GetCurrentDateTime() {
    var now = new Date(),
        hours = now.getHours(),
        ampm = hours < 12 ? "AM" : "PM";
    hours = (hours % 12 ) || 12;
    return (now.getMonth() + 1) + "-" 
        + now.getDate() + "-" 
        + now.getFullYear() + " " 
        + hours + ":" 
        + pad(now.getMinutes()) + " "
        + ampm;
}
function pad(n) {
    return (n < 10) ? ("0" + n) : n;
}

不需要省略onclick="setDateTimeOn(this);"

演示:http://jsfiddle.net/codeandcloud/p60at2x5/

可以使用以下代码:

var re = /__(.+)_/; 
// your control name was used an as example:
var str = 'GridView1__ctl2_AddButton0';
var m;
if ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
    re.lastIndex++;
    }
    // View your result using the m-variable.
    // m[0] == 'ctl2'
}

您可以使用通配符来查找包含特定字符串的ID。

$('[id*="ctl2"]')

如果页面上的其他元素在其ID中包含搜索字符串,则可能需要缩小目标范围。