Frank
Frank

Reputation: 63

Javascript prompt and submit

I want to get a value from JavaScript prompt and pass it to input for finally submit it

HTML

<form id="createdirForm"><input type="text" name="" id="createdir"/><form>

JavaScript

function createdir() {
    var newdirname;
    newdirname = prompt('Please input the directory name:', '');
    if (!newdirname) return;
    $('createdir').newdirname.value = newdirname;
    $('createdirForm').submit();
}

Upvotes: 1

Views: 3839

Answers (3)

user3589620
user3589620

Reputation:

You have some typo and have forgotten to add #. And the function is not executed.

HTML

<form id="createdirForm">
    <input type="text" name="dir" id="createdir" />
</form>

JavaScript

function createdir() {
    var newdirname;
    newdirname = prompt('Please input the directory name:', '');
    if (!newdirname) return;
    $('#createdir').value = newdirname;
    $('#createdirForm').submit();
}

createdir();

Upvotes: 0

Chin Leung
Chin Leung

Reputation: 14921

The reason why it's not working is because you're not calling the selector in your jQuery properly.

You might want to take a look at the jQuery Selector Tutorial.

Now to fix your problem, since you want to get the input and the form by the id attribute, just like in CSS, you need to use the hashtag (#) symbol.

So you would do:

$('#createdir').val(newdirname);
$('#createdirForm').submit();

Here's a working example: https://jsfiddle.net/vm4ah1L3/1/

Just a side note, you might want to add a name to your html input otherwise when you submit it to your PHP, you won't be able to retrieve the value since the name attribute is empty.

<input type="text" name="dirName" id="createdir">

And in your case, since you're declaring the variable newdirname and assign it right after, you could simply do the assignation in one line:

var newdirname = prompt("Please input a directory name: ");

Upvotes: 2

superjisan
superjisan

Reputation: 2064

It seems your jQuery selector is wrong. Try

$('#createdir').val(newdirname);
$('#createdirForm').submit();

jQuery uses the css selector logic, therefore to select an element by id you need to put the # before the selector name.

Also, to add a value to an input, you need to use val(param) with your value replaced in the param.

Upvotes: 0

Related Questions