Search code examples
javascriptsmshref

Is there a way to assign the user's input and/or selection into the message?


<input type="radio" name="T" id="twenT">20
<input type="radio" name="T" id="sixT">60
<input id="uIn"></input>
<a href="sms://+15552345678;?&body=CHANGE%20THIS"></a>
<button onclick="function()">

How do I make it so that the user selects one option or inputs text and then the text message changes to the text that was selected/entered. Pure JavaScript is preferred.


Solution

  • Try this

    I changed to name="T" to make them valid radios

    I also closed the A to make it valid. If you want to click the link and change, then we can remove the button

    const href = "sms://+15552345678;?&body="
    const sms = document.getElementById("sms");
    const uIn = document.getElementById("uIn");
    document.getElementById("changeMsg").addEventListener("click",function(e) {
      const val = document.querySelector("input[name=T]:checked");
      if (val) {
        sms.href = href.split("body=")
          .join(`body=${encodeURIComponent(val.value)}&uIn=${encodeURIComponent(uIn.value)}`)
        console.log(sms.href)
      }  
      else {
        console.log("radio not checked")
      }
    })
    <input type="radio" name="T" value="twenT">20
    <input type="radio" name="T" value="sixT">60
    <input id="uIn" type="text" value="" />
    <a id="sms" href="sms://+15552345678;?&body=CHANGE%20THIS">Call us</a>
    <button id="changeMsg" type="button">Change</button>