简体   繁体   English

如何从文本输入字段读取输入并将输入放入div

[英]how to read input from text input field and put input into div

I am trying to run this code. 我正在尝试运行此代码。 the code should take a string as input and put that input to a div and calculate the width of the div. 代码应将字符串作为输入并将该输入放入div并计算div的宽度。

here is code i have used. 这是我使用的代码。

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" value="" name="input">
<input type="submit" value="submit" name="submit">

<script>
var elem = '<div id="divitem" style="width:auto;"></div>';
$('body').append($(elem));
$("submit").click(function () {
var text = $(this).text();
value= $("input").val(text);
alert(value);
});

</script>
</body>
</html>

but i am not getting any output. 但我没有任何输出。 how to do this? 这个怎么做? please help me. 请帮我。

Try this paps! 试试这个棒棒糖!

Demo 演示版

This is similar to your problem. 这类似于您的问题。

HTML 的HTML

<div id="container">
   <input type="text" value="" id="inputtext">
   <input type="button" value="submit" id="submit">
</div>

Script 脚本

$(function(){
    var elem = '<span id="divitem"></span>';

    $('#container').append($(elem));

    $("#submit").click(function () {     
        $('#divitem').html($('#inputtext').val());
        alert($('#divitem').width());
    });
});

Here's a fiddle 这是一个小提琴

To obtain value from a text field you need to use this, 要从文本字段中获取价值,您需要使用它,

$('input[name="input"]').val();

and not .text() 而不是.text()

To answer your second question, you need to use this 要回答第二个问题,您需要使用此

$('#divitem').attr('style'); 

or 要么

$('#divitem').attr('width'); 

The problem is here: 问题在这里:

$("submit").click(function () {
    var text = $(this).text();
    value= $("input").val(text);
    alert(value);
});

$(this) refers to the element that you select, which is the submit button. $(this)指您选择的元素,即提交按钮。 You should replace the first line of the function with 您应该将函数的第一行替换为

$('input[name="input"]').text();

Finally, setting the html content of the div, will be done this way: 最后,通过以下方式设置div的html内容:

elem.html(test);

Hope this helps. 希望这可以帮助。 Have a great day. 祝你有美好的一天。

I have created a jsFiddle for your question http://jsfiddle.net/N4zFZ/ in JavaScript 我为您的问题http://jsfiddle.net/N4zFZ/在JavaScript中创建了jsFiddle

You can calculate width by 您可以通过以下方式计算宽度

`var width = $('#divId').attr('width');`

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

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