Gorschi Adrian Gorschi Adrian - 15 days ago 5
HTML Question

I need to color each second letter from a string in red jquery from a input

if could you help me, i am trying to color each second letter from a string from a input.
My code is:

from html:

<input type="text" id="textValue" class="form-control" placeholder="Scrieti Text">
<button type="button" class="btn btn-success" id="afisare">Afisati</button>
<div id="raspuns"></div>


from script:

$(document).ready(function () {

function makeText(textVal){
var index = textVal.length;
for(var i = 0; i < index; i++){
if(i % 2 == 1){
textVal[i].css("color","red");
}
}
return $('#raspuns').text(textVal);
}

$('#afisare').click(function () {
var textWrite = $('#textValue').val();
makeText(textWrite);
});
})

Answer

You can't set color to a specific letter. You need to add the letter in a tag and add styles in CSS.

$(document).ready(function () {

    function makeText(textVal) {

        var index = textVal.split('');
        for (var i = 0; i < index.length; i++) {
            var span = $('<span/>');
            if (i % 2 == 1) {
                span.html(textVal[i]).addClass('red');
                $('#raspuns').append(span);
            } else {
                span.html(textVal[i]).addClass('green');
                $('#raspuns').append(span);
            }
        }
        // return $('#raspuns').text(textVal);
    }

    $('#afisare').click(function () {
        var textWrite = $('#textValue').val();
        makeText(textWrite);
    });
})
#raspuns { font-size: 20px;}
.red {
    color:red;
}
.green {
    color:green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textValue" class="form-control" placeholder="Scrieti Text">
<button type="button" class="btn btn-success" id="afisare">Afisati</button>
<div id="raspuns"></div>

Comments