Question

Given this html...

<input id="txtbox-page" maxlength="4" />

how can I create a button or a link that executes a javascript function, where its parameter is the input box value?

I have to call a function, that is already in production, that has this format:

javascript:pageClient('?p=2');

where the number 2, has to be the value of the input box.

Was it helpful?

Solution

HTML

<button id="pageClientSubmitter">Click me</button>

JS

var pageClientSubmitter = document.getElementById('pageClientSubmitter');

pageClientSubmitter.onclick = function () {
  var val = document.getElementById('txtbox-page').value;
  pageClient('?p=' + val);
}

Demo

OTHER TIPS

HTML:

<a id="mylink" href="foo.bar">Link</a>

JS:

var box = document.getElementById('txtbox-page');
document.getElementById('mylink').addEventListener('click', function(){
    // Use `box` here
    pageClient('?p=' + +box.value);
}, false);

The second + is optional. I used it to convert to number in order to avoid injection attacks.

You could do something along these lines:

function GetTxtBoxValue() {
    var txtBoxPage = document.getElementByID("txtbox-page");
    pageClient('?p='+txtBoxPage.value);
}

Then bind that function to your form submission.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top