koffe14 koffe14 - 5 months ago 10
Javascript Question

Calling a function with if statments

I've made a function that is checking if anny textfield-element in the HTML containing the class "txt" has changed value sence the page last loaded. If anny text has been changed the function should return true in the if statement, otherwise false. However im only getting false. What im i doing wrong?

HTML:

<h3>Handlartext1...</h3>
<textarea class="txt">Hejsan</textarea><br/><br />

<h3>Handlartext2...</h3>
<textarea class="txt">Hejsan</textarea><br/><br />

<h3>Handlartext3...</h3>
<textarea class="txt">Hejsan</textarea><br/><br />

<input id="btnClick" type="button" value="Save changes" />


Script:

$('#btnClick').on("click",function() {
if(CheckTextChange()) {
alert('TRUE');
}
else {
alert('FALSE');
}
})


function CheckTextChange () {
var previousVal = $(".txt").get(0).defaultValue, currentVal = $(this).text();
//Checks if values have changed in elements containing class="txt"
$('.txt').each(function() {
//alert( $(this).text()); //or $(this).text();

if (currentVal != previousVal) {
return true;
}
else {
return false;
}
})
}

Answer

Your CheckTextChange function has a couple of issues:

  1. it will only ever check the first value
  2. It doesn't get the text properly

You could change it to something like this:

function CheckTextChange() {

    //Checks if values have changed in elements containing class="txt" 
    var isChanged = false;
    $('.txt').each(function () {
        var previousVal = $(this).get(0).defaultValue,
            currentVal = $(this).val();
        //alert( $(this).text()); //or $(this).text();

        if (currentVal != previousVal) {
            isChanged = true;
        }
    });

    return isChanged;
}

Fiddle