简体   繁体   中英

Js: Injecting values to multiple input fields

I have a form with an input field. I am able to inject a value to the input field, from a <script> . I get that value from a POST request.

But when i try to create another form, with the same input field (same name and id), value injection does not work.

I have not been able to troubleshoot the problem.

This is the html and route handler for the first case:

<form role="form" action="/scale" method="POST" id="sc-form-scale">
            <input type="hidden" name="filePath" id="filePath" value="">
            <input type="submit" value="Submit for Scaling">        
</form>


app.post('/scale', function(req, res) {
        
        var myFilePath = req.body.filePath;
        res.redirect('/');
        
        console.log(myFilePath);
        console.log(typeof myFilePath);

        
});

And this is for the second case:

<form role="form" action="/rotate" method="POST" id="sc-form-rotate">
                <input type="hidden" name="filePath" id="filePath" value="">
                <input type="submit" value="Submit for Rotation">       
</form>

    app.post('/rotate', function(req, res) {
    
        var myFilePath = req.body.filePath;
        res.redirect('/');
    
        
        console.log(myFilePath);
        console.log(typeof myFilePath);
    
    });

In the first case, everything works fine. This is what i get as a console.log output:

/home/user1/Desktop/myPart.step
string

But this is what i get in the second case:

string

As you can see, it is recognized as a string, but it's value is blank.

I don't why is that case. The code is exactly the same.

For both forms you have have the id filePath . Your ids should be unique, though names don't have to be. It sounds like you're setting the value by id, so you should either assign a unique id to each one and set them individually, or set them both to have the same class and use querySelectorAll or something like that to select multiple elements at once.

For instance, if you assign the class 'filePathClass' to both inputs, when you want to assign a value, you can do something like:

document.querySelectorAll('.filePathClass').forEach(function (fileInput) {
    fileInput.value = '...';
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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