Create an id for an element from a condition with Javascript

Asked

Viewed 1,855 times

0

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

In my code I will 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 this can be done?

2 answers

0


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

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

In the case,

$(this)

refers to who triggered the input event. But you can switch to another selector freely. However, I don’t know if to change the id is a good idea, so you could add another attribute:

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

Read more about the function .attr() here

  • Dude, that’s right, but I wanted this, so that another function could find this information, but when changing the id, it doesn’t count this new id

0

Maybe you can use jQuery’s 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');

This way it is not necessary to modify the element id attribute.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.