brandon cox brandon cox - 3 months ago 10
HTML Question

Change a textfield into a link with the value of the textfield when it has lost focus, and back again when you click the link

I am creating a Private Messaging system, and I wanted to make it start with a textbox for the "To" field, then when you click out of it for the first time (it starting as a text box) it turns into a Link such as this:
POC0bob (edit) and when you click the Username, it will take you to their profile in a blank tab, when you click the edit it all goes back to a textbox.

Link to jsfiddle with what I have so far.

$(document).ready(function() {
$('a.edit').click(function () {
var dads = $(this).parent().parent();
var dad = $(this).parent();
dads.find('label').hide();
dad.find('editusnm').hide();
dads.find('input[type="text"]').show().focus();
});

$('input[type=text]').focusout(function() {
var dad = $(this).parent();
$(this).hide();
dad.find('label').show();
});


});

I sorta stole that code, and edited it from another stackoverflow question, but it didn't help much.

That is kind of the basic idea I have, but I need the textbox and link to change based on the value of each other.

Answer

You can change the text and href attribute of the link on focusout by updating the focusout function to this:

$('input[type=text]').focusout(function() {
  var dad = $(this).parent();
  $(this).hide();
  dad.find('label').show();
  // Get username 
  var username = $(this).val();
  // Set the jQuery object to a variable so we're not getting it twice
  var $usernamelink = $('#username');
  // Set the link text to the text box value
  $usernamelink.text(username);
  // Set the link href incorporating the textbox value
  $usernamelink.attr("href", "/Profile/?user=" + username + "");
});

Then add an id to your anchor:

<p class="text-info"><a id="username" href="/Profile/?user=[Username]">Username</a></p>

See this Fiddle: http://jsfiddle.net/j2sgdx22/

Comments