2012-04-18 56 views
0

我有多个div,每个div都有一个文本框和一个标签。我需要填充在标签的一些文本时,文本框是.focusJquery获取div的当前标签并填充

脚本至今:

$(function() { 
    $('input:text').focus(function() { 
    //how do I get the current label and populate with some text? and when clicking on a 
    //different textbox, I want to clear the previous label and just show the current 
    //div's label with some data 
}); 
}); 

例如

<div> 
    @Html.TextBoxFor(model => model.Title) 
    <label> 
    </label> 
</div> 
<div> 
    @Html.TextBoxFor(model => model.Name) 
    <label> 
    </label> 
</div> 
<div> 
    @Html.TextBoxFor(model => model.Address) 
    <label> 
    </label> 
</div> 

thx!

回答

2

工作例如:

http://jsfiddle.net/KhQtx/

HTML:

<div> 
    <input type="text" title="Tittle" value=""/> 
    <label> 
    </label> 
</div> 
<div> 
    <input type="text" title="Name" value=""/> 
    <label> 
    </label> 
</div> 
<div> 
    <input type="text" title="Address" value=""/> 
    <label> 
    </label> 
</div>​ 

JS:

$('input:text').focus(function() { 
    // clean label 
    $('input:text').next('label').html(""); 

    // get input title 
    var title = $(this).attr('title');    

    // add html to label from input title 
    $(this).next('label').html(title); 
});​ 
+0

你真的,真的不需要发布截图。我们的浏览器渲染页面就好了。 – Blazemonger 2012-04-18 17:43:07

+0

真的相信我,有时真的会失败。我用很多代码回答了以前的问题,并且浪费了时间格式化所有代码。 – 2012-04-18 17:52:44

+0

把实际的代码放在这样的地步,人们可以很容易地复制和粘贴它。也不能保证您的图片托管服务将在明天发布。你需要做的是学习使用SO内置的代码格式工具。 – Blazemonger 2012-04-18 18:01:40

0
$(function() { 
    $('input:text').focus(function() { 
     $(this).siblings('label').empty().html('what you want..'); 
    }); 
}); 
0

你可以使用parentfind

var label = $(this).parent().find('label') 
0

尝试:

$('input:text').focus(function(){ 
    $(this).next().text('text here'); 
}); 
0
$('input:text').focus(function() { 
    $('input:text').next('label').html(""); // reset all first 
    $(this).next('label').html("Your text here"); 
}); 

See here

0
$(function() { 
    $('input:text').focus(function() { 
    // To put textboxvalue in label 
    $($(this).parent().find('label')).val($(this).val()); 
    // To put customvalue in label 
    $($(this).parent().find('label')).val("Hi i am a label"); 
}); 
}); 
0
$(function() { 
    $('input:text').focus(function(e){ 
     $('div label').text(""); 
     $(this).next('label').text('SomeText'); 
    }); 
});​ 

Example.

注:这将是更好,你指定一个类名到您的div如下

<div class="parentDiv"> 
    <input type="text" id="Title" /> 
    <label></label> 
</div> 

所以,你可以缩小你的选择一样

 $('div.parentDiv label').text(""); 
     $(this).next('label').text('SomeText'); 

这将避免其他div的标签为空。为你做的

+0

没有给div的ID需要。使用“这个”,你会得到当前焦点文本框。使用父母选择器,您将获得当前焦点文本框div,然后使用find我们将获得标签。所以它不会反映在所有其他标签上。 – 2012-04-18 17:54:12

+0

我认为你不明白实际的问题,也没有看到我的例子。你如何清除答案中的其他标签。看我的例子,并试图理解我说的。 – 2012-04-18 17:58:44

+0

是的,这是我的错误。但仍然不需要为每个div分配id。我们可以通过给每个标签分类名称,并在为标签分配一个值之前轻松实现它,我们将清除所有标签。例如

并且我们第一行的焦点函数将是$(“label.Clear”).val (“”) – 2012-04-18 18:03:46