jQuery Upsert

by Kyle Mitofsky

HTML

<form action="">
  <div>
    <input type="radio" id="ca" name="choice" value="A" /><label for='ca'>A</label>
    <input type="radio" id="cb" name="choice" value="B" /><label for='cb'>B</label>
    <input type="radio" id="cc" name="choice" value="C" /><label for='cc'>C</label>
  </div>
</form>














<div style='position:fixed;bottom:0;left:0; background:lightgray;width:100%;'>
    About these questions on StackOverflow:
    <ul style='margin:0;'>
      <li><a href='https://stackoverflow.com/a/46308265/1366033'>
          jQuery “get or create element” convenience method
      </a></li>
      <li><a href='https://stackoverflow.com/a/46308226/1366033'>
          jQuery create new child, or update existing child
      </a></li>
    </ul>
    
</div>

CSS

input[type="radio"]:checked+label {font-weight:bold;}

JavaScript

$.fn.upsert = function(selector, htmlString) {
	// upsert - find or create new element
  // find based on css selector   	https://api.jquery.com/category/selectors/
  // create based on jQuery()       http://api.jquery.com/jquery/#jQuery2
  var $el = $(this).find(".message");
  if ($el.length == 0) {
    // didn't exist, create and add to caller
    $el = $("<span class='message'></span>");
    $(this).append($el);
  }
	return $el;
}; 

$("input[name='choice']").click(function(){
  var $el = $(this).closest("form").upsert(".message", "<span class='message'></span>");
  // guaranteed to have element - update if we want
  $el.html("You've chosen "+this.value)
});