Search code examples
javascripteventsonclickbooleanhandler

toggle a boolean variable on an onclick event handler in javascript


Is there a way to toggle a boolean value on an onclick event handler in javascript? I thought the script I had would've worked but I guess not.

HTML (Not my full script)

<form action = "event_add.php" method = "post">
  <label>Details</label>
  <div class = "details">
    <span class = "editImg" onclick = "javascript:updateTextArea('<strong>','</strong>',bold)"><strong>B</strong></span>
    <span class = "editImg" onclick = "javascript:updateTextArea('<em>','</em>',ital)"><em>I</em></span>
    <textarea id = "txtAreaDetails" rows = "15" cols = "40"></textarea>
  </div>
</form>

Javascript:

var bold = false;
var ital = false;

function updateTextArea(beg_tag,end_tag,variable){
  if(variable == false){
    variable = true;
    var output = beg_tag;
  }else{
    variable = false;
    var output = end_tag;
  }
  var text = document.getElementById("txtAreaDetails").value;
  document.getElementById("txtAreaDetails").value = text + output;
}

What I'm trying to do is when the user clicks on the 'B', the textarea field will add a strong tag to it. Then if the user clicks it again, it will show the end tag /strong Same thing with the I, but with em and /em. The result I'm getting is always adding the beg_tag no matter how many times I click it.

I'm not too familiar with javascript, I do most of my programing in PHP so I'm not familiar if there's any built in functions to do this.


Solution

  • This should work. Instead of having a separate variable for each tag name, create an object with indices for each tag. Then you can access the true/false value by the name you pass in to updateTextArea. Also, you want to wrap bold and ital in quotes when you pass them in, your html does not do this.

    <form action = "event_add.php" method = "post">
      <label>Details</label>
      <div class = "details">
        <span class = "editImg" onclick = "updateTextArea('<strong>','</strong>','bold')"><strong>B</strong></span>
        <span class = "editImg" onclick = "updateTextArea('<em>','</em>','ital')"><em>I</em></span>
        <textarea id = "txtAreaDetails" rows = "15" cols = "40"></textarea>
      </div>
    </form>
    
    <script>
    
        var tagNames = {"bold": false, "ital": false};
    
        function updateTextArea(beg_tag,end_tag,variable){
          if(tagNames[variable] == false){
            tagNames[variable] = true;
            var output = beg_tag;
          }else{
            tagNames[variable] = false;
            var output = end_tag;
          }
          var text = document.getElementById("txtAreaDetails").value;
          document.getElementById("txtAreaDetails").value = text + output;
        }
    </script>