'How do i get textfield value in nativescript

i'm trying to get the text from my textfield in nativescript core.

let textField = args.object;
const yourSearch = textField.getViewById("requiredSkill").text;

the error i get is : cannot read property 'text' of undefined

please help



Solution 1:[1]

NativeScript View XML TextView

<TextView editable="true" id="requiredSkill"></TextView>

A simple button with tap event

<Button text="Button" tap="{{ onButtonTap }}" />

The JavaScript code behind for that tap event

var viewModel = observableModule.fromObject({
   onButtonTap: function (btargs) {
     let srcButton = btargs.object;
     const yourSearch =  srcButton.page.getViewById("requiredSkill").text;
   }
});

getViewById should be used on the <Page> model to search the entire page
or you must have a container/layout which should have an id, first find the layout using getViewById then again do another getViewById within that layout to find the TextView

so to answer your question, if it is a button click event, get the button and get the page of the button and find the view by Id

srcButton.page.getViewById

Solution 2:[2]

Thanks @Dickens , I am adding a specific example for NativeScript playground:

home-page.js:

var HomeViewModel = require("./home-view-model");
var homeViewModel = new HomeViewModel();

function pageLoaded(args) {
  var page = args.object;
  page.bindingContext = homeViewModel;
}

exports.pageLoaded = pageLoaded;

home-page.xml:

<Page loaded="pageLoaded" xmlns="http://www.nativescript.org/tns.xsd">
  <ActionBar title="Home">
    </ActionBar>
    <ScrollView>
        <StackLayout orientation="vertical" width="210" height="210"
            backgroundColor="lightgray">
            <TextField id="uspas" hint="Enter text..."  text="aaa,bbb"/>
            <Button text="Login" tap="{{ login }}" />
        </StackLayout>
    </ScrollView>
</Page>

home-view-model.js:

var observableModule = require("tns-core-modules/data/observable");

function HomeViewModel() {
  var viewModel = observableModule.fromObject({
    login: function (buttonArguments) {
      let srcButton = buttonArguments.object;
      const testo = srcButton.page.getViewById("uspas").text;
      var uspasCouple = testo.split(",");
      us = uspasCouple[0];
      pas = uspasCouple[1];
      console.log("Hai scritto:", us, pas);
    },
  });

  return viewModel;
}

module.exports = HomeViewModel;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 jumpjack