Blackarch
Blackarch

Reputation: 99

Add css using Onchange

How change code CSS` in JavaScript?

HTML :

<input type="text" name="text_field"  value="text" id ="hd" />

<div id="color">
    <input type="text" name="color" class ="border-bottom" value=""/>
</div>

Javascript :

$(document).ready(function() {
     $('#color input').change(function(){
          var css = $(this).attr("class");
          var z   = string(css);  // change type to string
          var x   = z+': 1px solid'; // mix 
          $("#hd").css(css,$(this).val());
     });
});

I need write 1px solid in field, I try mix from border-bottom and 1px solid to new variable (border-bottom : 1px solid), then I just input color type like red/blue/dll.

Please see here for more understanding https://jsfiddle.net/1Lmhj3xp/1/

Upvotes: 2

Views: 1897

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

The change event not made to track change in text fields you should use keypress or ipnput event instead :

$('#color input').on('input', function(){

If you want to just input color you could fix 1px solid to be static:

$("#hd").css(css, "1px solid "+$(this).val());

Hope this helps.


Snippet

$(document).ready(function() {
  $('#color input').on('input', function(){
        var css = $(this).attr("class");
        $("#hd").css(css, "10px solid "+$(this).val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
TEXT <input type="text" name="text_field"  value="text" id ="hd" />

<div id="color">
	CSS <input type="text" name="color" class ="border-bottom" value=""/>
</div>
Try input in CSS 1px solid red (onchange)

Upvotes: 2

rrk
rrk

Reputation: 15866

You can use (css, x + this.value) to set the css.

$('#color input').change(function() {
  var css = $(this).attr("class");
  var x = '1px solid '; // mix 
  $("#hd").css(css, x + this.value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="text_field" value="text" id="hd" />
<br><br>
<div id="color">
  <input type="text" name="color" class="border-bottom" value="" placeholder="Enter color"/>
</div>

Upvotes: 2

Related Questions