将文本输入的值传递给javascript函数

将文本输入的值传递给javascript函数

本文介绍了将文本输入的值传递给javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的html文件中,我调用了一个带有两个参数的javascript函数,其中第二个参数是应该保存的文件的名称。

 < a id =record_buttononclick =Recorder.record('audio','test.wav');  HREF = JavaScript的:无效(0); title =Record>< img src =images / record.pngwidth =24height =24alt =Record/>< / a> 

我想制作一个动态变量,它从文本字段获取值并将其作为第二个参数(而不是test.wav),因此用户可以确定文件的名称。

 < label for =文件名>文件名< /标签> 
< input name =filenametype =text>

谢谢。

解决方案

如果你给用户输入一个 id 属性,这样会更容易:

 < input name =filenameid =filenametype =text> 

现在您可以通过以下方式访问Javascript中的值:


$ b $ $

  document.getElementById('filename')。请注意,如果您不控制 Recorder.record()方法,则需要首先验证用户输入(至少要验证他们已经进入了一些)。我建议把它移到一个单独的函数中,例如: 

 函数recordToFilename(){
var input = document .getElementById('filename'),
fileName = input.value;
if(fileName){
Recorder.record('audio',fileName);
} else {
alert('请输入文件名!');
input.focus();


然后使用该函数:

 < a id =record_buttononclick =recordToFilename(); HREF = JavaScript的:无效(0); title =Record>< img src =images / record.pngwidth =24height =24alt =Record/>< / a> 

工作示例:


Inside my html file I call a javascript function that takes two parameters, where the second parameter is the name of a file that should be saved.

<a id="record_button" onclick="Recorder.record('audio', 'test.wav');" href="javascript:void(0);" title="Record"><img src="images/record.png" width="24" height="24" alt="Record"/></a>

I would like to make a dynamic variable that takes the value from a textfield and forward that as the second parameter (instead of test.wav), so the user can determine the name of the file.

<label for="filename">Filename</label>
<input name="filename" type="text">

Thanks.

解决方案

This is easier if you give your user input an id attribute:

<input name="filename" id="filename" type="text">

Now you can access the value in Javascript with:

document.getElementById('filename').value

Note that, if you aren't controlling the Recorder.record() method, you'll need to validate the user input first (at a minimum, to verify that they've entered something). I'd recommend moving this to a separate function, e.g.:

function recordToFilename() {
    var input = document.getElementById('filename'),
        fileName = input.value;
    if (fileName) {
        Recorder.record('audio', fileName);
    } else {
        alert('Please enter a filename!');
        input.focus();
    }
}

Then just use that function:

<a id="record_button" onclick="recordToFilename();" href="javascript:void(0);" title="Record"><img src="images/record.png" width="24" height="24" alt="Record"/></a>

Working example: http://jsfiddle.net/nrabinowitz/GFpRy/

这篇关于将文本输入的值传递给javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 02:33