Fetch or clone data from input field

Issue

I am currently having some issues with the following script:

    <input name="MYNEWVALUE" class="MYNEWVALUE" maxlength="20" type="text" id="MYNEWVALUE">
    <a onclick="addURL(this)" href="<?php echo $escaped_url?>">Click this</a>
    
    <script>
    function addURL(element)
    {
        $(element).attr('href', function() {
            return this.href + '?notes=...';
        });
    }
    </script>

As you can see I have an input field which I called MYNEWVALUE and a Button with a Javascript function. This button once clicked adds a specific parameter to my URL e.g. https://myurl.com/?notes=…

What I am currently trying to achieve is to fetch the data from the input field (as soon as the Button has been clicked) and use it or clone it directly in conjunction to this.href + ‘?notes=MYNEWVALUE‘;

So If I would enter Testing the final URL to be passed on should become https://myurl.com/?notes=Testing

Is there a way to intercept or clone this value? Some expert help would be greatly appreciated, thank you.

Solution

What you can do is change how you’re handling the event handling and simplify it like so:

<a href="<?php echo $escaped_url?>" id="button">Click this</a>

<script>
    $("#button").on("click", function() {
        this.href += "?notes=" + $("#MYNEWVALUE").val();
    });
</script>

jQuery .click() documentation as follows (note you cannot use an ES6 function for this one due to the ES6 arrow function’s lexical this).

Answered By – Jack Bashford

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.