Jump to content



Photo

JQuery not replacing text as it should

jquery replace

  • Please log in to reply
2 replies to this topic

#1 gregor

gregor

    #include 'mybrain.h'

  • Joined: 03-August 01
  • Location: Slovenia
  • OS: Windows 7
  • Phone: Sony Xperia Z

Posted 18 December 2012 - 13:04

Hi, here's my code:

HTML
<a href="" class="button off"><div class="button toggle">on</div><img src="http://icons.iconarchive.com/icons/artdesigner/urban-stories/128/House-icon.png" /><br />DOOR</a>


JQuery code AFTER HTML (in <body> tags):
<script>
$(".button").click(function () {
	$(".toggle", this).text(($(".toggle", this).text() == "on") ? "off" : "on");
});</script>

what it should do?
- if button toggle <div> element is set to "on", set it to off. otherwise, set ti to on. :)

what it does?
- it shows the replacement but the text imediately jumps back to "on". :(((


I'm going crazy, clueless where's the catch???

Help me please :(


#2 lunamonkey

lunamonkey

    Ten years on Neowin.

  • Joined: 28-May 03
  • Location: Swindon, England

Posted 18 December 2012 - 13:15

You've got nested .buttons. It's probably causing some issues.

the callback inside your text() is looking for another nested .toggle inside "this", which is the Div.toggle. I'm sure it's getting itself in a twist.

Let me get a page running....


You might need to prevent the default.

<script>
$(".button").click(function (e) {
e.preventDefault();
		$(".toggle", this).text(($(".toggle", this).text() == "on") ? "off" : "on");
});</script>

edit : solution

#3 OP gregor

gregor

    #include 'mybrain.h'

  • Joined: 03-August 01
  • Location: Slovenia
  • OS: Windows 7
  • Phone: Sony Xperia Z

Posted 18 December 2012 - 18:37

Thank you @lunaquote!

Works as charm! :)))



Click here to login or here to register to remove this ad, it's free!