0

how can i change the text of a button when clicked? and change it back when clicked again? i have this javascript i made.and its not giving me what i want.please help?

    $('#addbtn').click(function (){
    if(document.getElementById('addMat').style.display == "none"){
        document.getElementById('addMat').style.display= "inline";
        $(this).val('Cancel');
    }else
        document.getElementById('addMat').style.display= "none";
        $(this).val('Add Material');
});
5
  • Why are you using jQuery ($('#addbtn').click(function (){) and pure JS (document.getElementById('addMat').style.display == "none")?
    – Mooseman
    Jan 13, 2013 at 16:45
  • I "think" your $(this) will reference the #addMat element, and not the #addbtn element. Is that what you want? A tiny bit of HTML will help since I am not sure which element is the button.
    – Leeish
    Jan 13, 2013 at 16:46
  • You can do this in pure CSS using the focus() Psuedo Class. Create two buttons, with one display none. On focus() show the other button with a higher z-index. Twitter uses this format in its tweet buttons
    – Ray
    Jan 13, 2013 at 16:48
  • @Mooseman is that wrong? sorry.im just new here.
    – chris
    Jan 13, 2013 at 16:50
  • @Leeish, can i reference the button inside this function?
    – chris
    Jan 13, 2013 at 16:51

3 Answers 3

2

Just do it all with jQuery syntax:

$('#addbtn').click(function (){
    var addMat = $('#addMat');
    if( addMat.css('display')  === 'none' ) {
      addMat.css('display','inline');
      $(this).val('Cancel');
    } else {
      addMat.css('display','none');
      $(this).val('Add Material');
    }
});
0
2
$('#addbtn').click(function (){
    if(document.getElementById('addMat').style.display === "none"){
        document.getElementById('addMat').style.display = "inline";
        $(this).attr("value","Cancel");
    }else{
        document.getElementById('addMat').style.display = "none";
        $(this).attr("value","Add Material");
    }
});

or Better...

$('#addbtn').click(function (){
    if( $('#addMat').css('display')  === 'none' ){
      $('#addMat').css('display','inline');
      $(this).attr("value","Cancel");
    } else {
      $('#addMat').css('display','none');
      $(this).attr("value","Add Material");
    }
});
1
  • .attr will only work if the OP is using jquery versions older than 1.6
    – Ray
    Jan 13, 2013 at 16:57
0
$(this).prop('value', 'Cancel'); 

or

$(this).html('Cancel');

The Best way to do it is create a button and put a span tag around the text

$("span", this).text("My NEW Text");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.