Create an id for an element from a condition with Javascript

0

Is there any way in JavaScript or jQuery to include a Id in a div within a condition?

In my code I'll exemplify:

 $('#TxtDesc').on('input', function(){
   var value = $(this).val();
   var progressValue = $('#progressText div');
   var color, percent = 0;
if(value.length <= 100){
  color = "red";
  percent = 15;
}else if(value.length <= 199){
  color = "yellow";
  percent = 50;
}else{
  color = "#32CD32";
  percent = 100;
  /* Gostaria que nessa condição fosse adicionado um id 
    para a div onde o script roda */
}

 var Valor = value.length;



progress(percent, $('#progressText'), 300);
progressValue.css("background", color);
$('#progressText').css("border", "1px solid " + color);

 }); 

Is there any way to do this?

    
asked by anonymous 14.09.2017 / 16:17

2 answers

0

If you just add or change the id attribute, just do:

$(this).attr('id', 'SeuValor');

In this case,

$(this)

refers to who fired the 'input' event. But you can switch to another dial freely. But I do not know if changing id is a good idea, so you could add another attribute:

$(this).attr('SeuAtributo', 'SeuValor');

Read more about the .attr() here

    
14.09.2017 / 16:24
0

Maybe you can do this by using the jQuery date function:

$('div').data('id','valor-do-id');

In Html, something like this will be generated:

<div data-id="valor-do-id"></div>

You can capture the data this way:

var id = $('div').data('id');

Doing so does not need to modify the id attribute of the element.

    
14.09.2017 / 16:29