获取输入值并通过查询字符串传递

时间:2015-01-18 10:28:09

标签: javascript jquery html

我正在尝试获取用户在输入框中输入的文本的值,但问题是,不是获取用户键入的值,而是获取输入的预设值“undefined”

HTML

<input type="text" id="userInput" value="" name="title" 
       placeholder="Enter the name here" required="required"/>
<input type="button" id="text_value" value="Set Input"/>
   <!-- I have this button here because I think maybe 
    I should have a button to change default value but
    I don't know the javascript to do this -->

的Javascript

// Gets input value id 

    var theuserInput = $("#userInput").val();

我没有显示查询字符串代码的原因是因为输入值是在url中传递的,但问题是传递了默认输入值'undefined'而不是实际的用户输入。

任何解决方案?

其他代码

好的,所以这里是查询字符串,当你点击'pass'按钮时,输入会在querystring中传递:

$('.pass').click(function() {
    window.location.href = 'http://lala.com/passing.php?input=' + theuserInput + '';
    return false;
});

2 个答案:

答案 0 :(得分:3)

请改为尝试:

$('.pass').click(function() {
    var theuserInput = $("#userInput").val();
    window.location.href = 'http://lala.com/passing.php?input=' + theuserInput + '';
    return false;
});

在调用this方法之前删除了val()

您获得undefined的原因是因为theuserInput未在传递给#click方法的匿名函数范围中定义。 JS引擎尝试递归地在“englobing”范围内找到theuserInput,直到达到全局范围或在连续的“englobing”范围之一中找到theuserInput值。由于无法在任何范围内找到变量theuserInput,因此会影响默认值undefined

答案 1 :(得分:0)

var theuserInput = document.getElementById("userInput").value;