Hi I'm trying to build a form (not important but only to know: in bootstrap 5) with several fields and on one of these, where a url will be inserted, capture the value written inside and launch that page in a new tab, all before the form submission.
For the basic function it's ok, but I would like the <a href tag to be "disabled"(not clickable) as long as it is empty and starts working when someone writes into it. Could you give me some tips?
This is the code:
Html:
<div style="margin:10px;padding:10px 0 0 0;">
<label for="fUrl"><i ></i>URL</label>
<div >
<input type="text" maxlength="255" id="fUrl" name="fUrl" value="">
<span >
<a href="" target="_blank" id="HreffUrl" onclick="changeHrefCol()" title="Anteprima">A</a>
</span>
</div>
</div>
javascript:
function changeHrefCol(){
// Selecting the input element and get its value
let inputVal = document.getElementById("fUrl").value;
if(inputVal !== null && inputVal !== '') {
// Set it for the href
document.getElementById("HreffUrl").setAttribute("href", `${inputVal}`);
}
// Test
console.log(inputVal);
}
CodePudding user response:
By attaching the input
event listener to the input field you can change the .href
immediately when the input changes. And when the input is empty (this.value.length==0
)
you can remove the .href
attribute altogether, making it "unclickable".
const a=document.getElementById("HreffUrl");
document.getElementById("fUrl").addEventListener("input",function(){
if(this.value.length)
a.href=this.value;
else a.removeAttribute("href");
console.log(a.href);
})
<div style="margin:10px;padding:10px 0 0 0;">
<label for="fUrl"><i ></i>URL</label>
<div >
<input type="text" maxlength="255" id="fUrl" name="fUrl" value="">
<span >
<a target="_blank" id="HreffUrl" title="Anteprima">A</a>
</span>
</div>
</div>
CodePudding user response:
No need to make it an <a>
tag. That will just make what you want to do harder. Perhaps make it a <button>
, then when clicked, check if the input has a value. If the value is there, use javascript to open the new tab, with window.open(URL, '_blank');
You can also submit a form after that using javascript if needed.